package com.caifu.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.PageDo;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.controller.AbstractController;
import com.caifu.enums.*;
import com.caifu.excel.userInfoExcel.DownUserInfoExcel;
import com.caifu.excel.userInfoExcel.UserInfoExcel;
import com.caifu.excel.userInfoExcel.UserInfoExcelError;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.util.AesMyUtil;
import com.caifu.util.CheckIdCardUtil;
import com.caifu.util.Constance;
import com.caifu.util.Util;
import com.caifu.vo.bmfw.BmUserinfoVo;
import com.caifu.vo.report.ReportRecordPageVO;
import com.caifu.vo.report.ReportRecordVO;
import com.caifu.vo.userinfoVo.UserInfoVO;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * ClassName : UserInfoService
 *
 * @author :  yb
 * @description ： 老人档案
 * @date : 2020-10-12 14:07
 */
@Service
public class UserInfoService extends AbstractController {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserInfoContactMapper userInfoContactMapper;
    @Resource
    private YsLabelMapper ysLabelMapper;
    @Resource
    private ReportRecordMapper reportRecordMapper;
    @Resource
    private ReportRecordLogMapper reportRecordLogMapper;
    @Resource
    private SysOrganizationMapper sysOrganizationMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private YlCostMapper ylCostMapper;
    @Resource
    private BmUserinfoMapper bmUserinfoMapper;
    @Resource
    private SysUserDataAuthMapper sysUserDataAuthMapper;
    @Resource
    private UserInfoSynthesizeMapper userInfoSynthesizeMapper;
    @Resource
    private UserInfoHistoryMapper userInfoHistoryMapper;


    /**
     * 判断表头是否一致
     */
    private boolean isTrueHead = true;


    /**
     * 获取老人档案分页
     *
     * @param status 状态 1-正常 8-去世 9-删除
     * @return Result
     */
    public Result<Object> getUserInfoPageList(UserInfoVO vo, String status) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //状态 1-正常 8-去世 9-删除
        queryWrapper.eq("status", status);
        //列表页 查询条件给queryWrapper 赋值
        setQueryWrapperForQueryUserInfo(queryWrapper, vo);

        IPage<UserInfo> userInfoPage = userInfoMapper.selectPage(new Page<>(vo.getCurrentPage(), vo.getPageSize()), queryWrapper);
        //数据转化 页面展示
        userInfoPage.getRecords().forEach(this::transformUserInfoForPageList);

        List<UserInfo> userInfoList = userInfoPage.getRecords();
        return ResultUtil.getPageDataSuccess(new PageDo<>(vo.getCurrentPage(), vo.getPageSize(), Integer.parseInt(userInfoPage.getTotal() + ""), userInfoList));
    }


    public Result<Object> getUserInfoSynthesizePageList(UserInfoVO vo, String status) {

        QueryWrapper<UserInfoSynthesize> queryWrapper = new QueryWrapper<>();
        //状态 1-正常 8-去世 9-删除
        queryWrapper.eq("status", status);
        //列表页 查询条件给queryWrapper 赋值
        setQueryWrapperForQueryUserInfoSynthesize(queryWrapper, vo);

        IPage<UserInfoSynthesize> userInfoPage = userInfoSynthesizeMapper.selectPage(new Page<>(vo.getCurrentPage(), vo.getPageSize()), queryWrapper);
        //数据转化 页面展示
        userInfoPage.getRecords().forEach(this::transformUserInfoSynthesizeForPageList);

        List<UserInfoSynthesize> userInfoList = userInfoPage.getRecords();
        return ResultUtil.getPageDataSuccess(new PageDo<>(vo.getCurrentPage(), vo.getPageSize(), Integer.parseInt(userInfoPage.getTotal() + ""), userInfoList));
    }


    /**
     * 查询条件 赋值
     */
    private void setQueryWrapperForQueryUserInfo(QueryWrapper<UserInfo> queryWrapper, UserInfoVO vo) {
        //户籍
        if (Util.isNotNull(vo.getHouseholdRegister())) {
            queryWrapper.eq("household_register", vo.getHouseholdRegister());
        }
        //所在地区
        if (Util.isNotNull(vo.getLocation())) {
            queryWrapper.eq("location", vo.getLocation());
        }
        //常住人口
        if (Util.isNotNull(vo.getIsLongStay())) {
            queryWrapper.eq("is_long_stay", vo.getIsLongStay());

        }
        //年龄段
        if (Util.isNotNull(vo.getStartAge()) && Util.isNotNull(vo.getEndAge())) {
            queryWrapper.between("age", vo.getStartAge(), vo.getEndAge());
        }

//        int one = 1;
//        int two = 2;
//        int three = 3;
//        int four = 4;
//        int five = 5;
//        int six = 6;
//        if (Util.isNotNull(vo.getAge())) {
//            //1-60岁以下  2- 60-69岁 3 - 70-79岁 4-90-99岁 5-100岁及以上  6-80-89岁
//            if (one == vo.getAge()) {
//                queryWrapper.lt("age", 60);
//            } else if (two == vo.getAge()) {
//                queryWrapper.between("age", 60, 69);
//            } else if (three == vo.getAge()) {
//                queryWrapper.between("age", 70, 79);
//            } else if (four == vo.getAge()) {
//                queryWrapper.between("age", 90, 99);
//            } else if (five == vo.getAge()) {
//                queryWrapper.ge("age", 100);
//            } else if (six == vo.getAge()) {
//                queryWrapper.between("age", 80, 89);
//            }
//        }
        //性别
        if (Util.isNotNull(vo.getUserSex())) {
            queryWrapper.eq("user_sex", vo.getUserSex());
        }
        //目前养老状况
        if (Util.isNotNull(vo.getPensionStatus())) {
            queryWrapper.eq("pension_status", vo.getPensionStatus());
        }
        //政治面貌
        if (Util.isNotNull(vo.getPolitical())) {
            queryWrapper.in("political", Arrays.asList(vo.getPolitical().split(",")));
        }
        //社保类型
        if (Util.isNotNull(vo.getSocialSecurityType())) {
            queryWrapper.in("social_security_type", Arrays.asList(vo.getSocialSecurityType().split(",")));
        }
        //居家状况
        if (Util.isNotNull(vo.getLiveHomeStatus())) {
            queryWrapper.in("live_home_status", Arrays.asList(vo.getLiveHomeStatus().split(",")));
        }
        //居家状况
        if (Util.isNotNull(vo.getLiveHomeStatus())) {
            queryWrapper.in("live_home_status", Arrays.asList(vo.getLiveHomeStatus().split(",")));
        }
        //照顾人群
        if (Util.isNotNull(vo.getCareCrowd())) {
            queryWrapper.in("care_crowd", Arrays.asList(vo.getCareCrowd().split(",")));
        }
        //居住状况
        if (Util.isNotNull(vo.getLiveCondition())) {
            queryWrapper.eq("live_condition", vo.getLiveCondition());
        }
        //关键字
        if (Util.isNotNull(vo.getSearchContent())) {
            queryWrapper.like("user_name", vo.getSearchContent());
        }
        //死亡时间段
        if (Util.isNotNull(vo.getDeathStartDate()) && Util.isNotNull(vo.getDeathEndDate())) {
            queryWrapper.between("death_date", vo.getDeathStartDate().replace("-", ""), vo.getDeathEndDate().replace("-", ""));
        }


        //所属机构
        String userNo = getUser().getUserNo() + "";
        if (Util.isNotNull(vo.getOrgId())) {
            //选择组织架构的时候 根据权限判断
            List<String> orgIds = new ArrayList<>();
            getOrgIds(orgIds, vo.getOrgId());
            queryWrapper.in("belong_organization", getOrgIdsOfAuth(orgIds, userNo));
            //            queryWrapper.and(wrapper -> wrapper.in("belong_organization", orgIds).or().in("belong_organization", orgIds));
        } else {
            //没有选择组织架构的时候 直接拿权限的
            queryWrapper.in("belong_organization", getOrgIdsOfAuth(null, userNo));
        }

    }


    private void setQueryWrapperForQueryUserInfoSynthesize(QueryWrapper<UserInfoSynthesize> queryWrapper, UserInfoVO vo) {
        //户籍
        if (Util.isNotNull(vo.getHouseholdRegister())) {
            queryWrapper.eq("household_register", vo.getHouseholdRegister());
        }
        //所在地区
        if (Util.isNotNull(vo.getLocation())) {
            queryWrapper.eq("location", vo.getLocation());
        }
        //常住人口
        if (Util.isNotNull(vo.getIsLongStay())) {
            queryWrapper.eq("is_long_stay", vo.getIsLongStay());

        }
        //年龄段
        if (Util.isNotNull(vo.getStartAge()) && Util.isNotNull(vo.getEndAge())) {
            queryWrapper.between("age", vo.getStartAge(), vo.getEndAge());
        }
//        int one = 1;
//        int two = 2;
//        int three = 3;
//        int four = 4;
//        int five = 5;
//        int six = 6;
//        if (Util.isNotNull(vo.getAge())) {
//            //1-60岁以下  2- 60-69岁 3 - 70-79岁 4-90-99岁 5-100岁及以上  6-80-89岁
//            if (one == vo.getAge()) {
//                queryWrapper.lt("age", 60);
//            } else if (two == vo.getAge()) {
//                queryWrapper.between("age", 60, 69);
//            } else if (three == vo.getAge()) {
//                queryWrapper.between("age", 70, 79);
//            } else if (four == vo.getAge()) {
//                queryWrapper.between("age", 90, 99);
//            } else if (five == vo.getAge()) {
//                queryWrapper.ge("age", 100);
//            } else if (six == vo.getAge()) {
//                queryWrapper.between("age", 80, 89);
//            }
//        }
        //性别
        if (Util.isNotNull(vo.getUserSex())) {
            queryWrapper.eq("user_sex", vo.getUserSex());
        }
        //目前养老状况
        if (Util.isNotNull(vo.getPensionStatus())) {
            queryWrapper.eq("pension_status", vo.getPensionStatus());
        }
        //政治面貌
        if (Util.isNotNull(vo.getPolitical())) {
            queryWrapper.in("political", Arrays.asList(vo.getPolitical().split(",")));
        }
        //社保类型
        if (Util.isNotNull(vo.getSocialSecurityType())) {
            queryWrapper.in("social_security_type", Arrays.asList(vo.getSocialSecurityType().split(",")));
        }
        //居家状况
        if (Util.isNotNull(vo.getLiveHomeStatus())) {
            queryWrapper.in("live_home_status", Arrays.asList(vo.getLiveHomeStatus().split(",")));
        }
        //居家状况
        if (Util.isNotNull(vo.getLiveHomeStatus())) {
            queryWrapper.in("live_home_status", Arrays.asList(vo.getLiveHomeStatus().split(",")));
        }
        //照顾人群
        if (Util.isNotNull(vo.getCareCrowd())) {
            queryWrapper.in("care_crowd", Arrays.asList(vo.getCareCrowd().split(",")));
        }
        //居住状况
        if (Util.isNotNull(vo.getLiveCondition())) {
            queryWrapper.eq("live_condition", vo.getLiveCondition());
        }
        //关键字
        if (Util.isNotNull(vo.getSearchContent())) {
            queryWrapper.like("user_name", vo.getSearchContent());
        }
        //死亡时间段
        if (Util.isNotNull(vo.getDeathStartDate()) && Util.isNotNull(vo.getDeathEndDate())) {
            queryWrapper.between("death_date", vo.getDeathStartDate().replace("-", ""), vo.getDeathEndDate().replace("-", ""));
        }


        //所属机构
        String userNo = getUser().getUserNo() + "";
        if (Util.isNotNull(vo.getOrgId())) {
            //选择组织架构的时候 根据权限判断
            List<String> orgIds = new ArrayList<>();
            getOrgIds(orgIds, vo.getOrgId());
            queryWrapper.in("belong_organization", getOrgIdsOfAuth(orgIds, userNo));
            //            queryWrapper.and(wrapper -> wrapper.in("belong_organization", orgIds).or().in("belong_organization", orgIds));
        } else {
            //没有选择组织架构的时候 直接拿权限的
            queryWrapper.in("belong_organization", getOrgIdsOfAuth(null, userNo));
        }

    }

    /**
     * 权限 orgid 判断出所有的
     *
     * @param orgIds 页面选择 orgId
     * @return List
     */
    private List<String> getOrgIdsOfAuth(List<String> orgIds, String userNo) {
        //用户权限的 orgId
        List<SysUserDataAuth> userDataAuthList = getUserDataAuthList(userNo);
        List<String> authList = new ArrayList<>();
        userDataAuthList.forEach(model -> authList.add(model.getOrgId() + ""));
        //        System.out.println(authList);
        if (Util.isNull(orgIds)) {
            return authList;
        }

        List<String> returnList = new ArrayList<>();
        orgIds.forEach(orgId -> {
            if (authList.contains(orgId)) {
                returnList.add(orgId);
            }
        });
        //        System.out.println(returnList);
        return returnList;
    }


    private void getOrgIds(List<String> orgIds, String orgId) {
        SysOrganization sysOrganization = getOrganizationByOrgId(orgId);
        // 获取orgIds集合
        orgIds.add(String.valueOf(sysOrganization.getOrgId()));
        getChildOrganization(orgIds, sysOrganization);
    }

    private SysOrganization getOrganizationByOrgId(String orgId) {
        QueryWrapper<SysOrganization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("org_id", orgId);
        organizationQueryWrapper.eq("state", "1");
        return sysOrganizationMapper.selectOne(organizationQueryWrapper);
    }

    private void getChildOrganization(List<String> list, SysOrganization organization) {
        //是否存在子组织，0否，1-是
        String isExistChild = "1";
        if (isExistChild.equals(organization.getIsChildExist())) {
            QueryWrapper<SysOrganization> organizationQueryWrapper = new QueryWrapper<>();
            organizationQueryWrapper.eq("parent_org_id", organization.getOrgId());
            organizationQueryWrapper.eq("state", "1");
            List<SysOrganization> orgList = sysOrganizationMapper.selectList(organizationQueryWrapper);
            if (Util.isNotNull(orgList) && orgList.size() > 0) {
                orgList.forEach(model -> {
                    list.add(String.valueOf(model.getOrgId()));
                    getChildOrganization(list, model);
                });
            }
            organization.setChildren(orgList);
        }
    }


    private List<SysUserDataAuth> getUserDataAuthList(String userNo) {
        QueryWrapper<SysUserDataAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_no", userNo);
        return sysUserDataAuthMapper.selectList(queryWrapper);
    }


    private void transformBmUserInfoForPageList(UserInfo userInfo) {
        //户籍类型
        if (Util.isNotNull(userInfo.getHouseholdRegister())) {
            userInfo.setHouseholdRegister(getLabelNameByLabelCode(userInfo.getHouseholdRegister()));
        }
        //性别
        if (Util.isNotNull(userInfo.getUserSex())) {
            userInfo.setUserSex(SexTypeEnum.getName(userInfo.getUserSex()));
        }
        //管辖机构
        if (Util.isNotNull(userInfo.getBelongOrganization())) {
            //转成orgName
            SysOrganization sysOrganization = getOrganizationByOrgId(userInfo.getBelongOrganization());
            if (Util.isNotNull(sysOrganization)) {
                userInfo.setBelongOrganization(sysOrganization.getOrgName());
            }
        }
        //社保类型
        if (Util.isNotNull(userInfo.getSocialSecurityType())) {
            userInfo.setSocialSecurityType(getLabelNameByLabelCode(userInfo.getSocialSecurityType()));
        }
        //养老状况
        if (Util.isNotNull(userInfo.getPensionStatus())) {
            userInfo.setPensionStatus(getLabelNameByLabelCode(userInfo.getPensionStatus()));
        }

        //出生时间
        if (Util.isNotNull(userInfo.getBirthDate())) {
            userInfo.setBirthDate(transformDateForLoad(userInfo.getBirthDate()));
        }

        //退休时间
        if (Util.isNotNull(userInfo.getRetireTime())) {
            userInfo.setRetireTime(transformDateForLoad(userInfo.getRetireTime()));
        }
    }


    private void transformUserInfoForPageList(UserInfo userInfo) {
        //户籍类型
        if (Util.isNotNull(userInfo.getHouseholdRegister())) {
            userInfo.setHouseholdRegister(getLabelNameByLabelCode(userInfo.getHouseholdRegister()));
        }
        //户籍所在地
        if (Util.isNotNull(userInfo.getRegisterAreaOfResidence())) {
            userInfo.setRegisterAreaOfResidence(getLabelNameByLabelCode(userInfo.getRegisterAreaOfResidence()));
        }
        //管辖机构
        if (Util.isNotNull(userInfo.getBelongOrganization())) {
            userInfo.setBelongOrganization(sysOrganizationMapper.selectById(userInfo.getBelongOrganization()).getOrgName());
        }
        //所在地区
        if (Util.isNotNull(userInfo.getLocation())) {
            userInfo.setLocation(getLabelNameByLabelCode(userInfo.getLocation()));
        }
        //性别
        if (Util.isNotNull(userInfo.getUserSex())) {
            userInfo.setUserSex(SexTypeEnum.getName(userInfo.getUserSex()));
        }
        //离世时间
        if (Util.isNotNull(userInfo.getDeathDate())) {
            userInfo.setDeathDate(transformDateForLoad(userInfo.getDeathDate()));
        }
        //常住人口
        if (Util.isNotNull(userInfo.getIsLongStay())) {
            if ("1".equals(userInfo.getIsLongStay())) {
                userInfo.setIsLongStay("是");
            } else if ("2".equals(userInfo.getIsLongStay())) {
                userInfo.setIsLongStay("否");
            } else {
                userInfo.setIsLongStay("");
            }
        }
        //证件号
        if (Util.isNotNull(userInfo.getUserPid())) {
            try {
                userInfo.setUserPid(AesMyUtil.Decrypt(userInfo.getUserPid()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void transformUserInfoSynthesizeForPageList(UserInfoSynthesize userInfo) {
        //户籍类型
        if (Util.isNotNull(userInfo.getHouseholdRegister())) {
            userInfo.setHouseholdRegister(getLabelNameByLabelCode(userInfo.getHouseholdRegister()));
        }
        //户籍所在地
        if (Util.isNotNull(userInfo.getRegisterAreaOfResidence())) {
            userInfo.setRegisterAreaOfResidence(getLabelNameByLabelCode(userInfo.getRegisterAreaOfResidence()));
        }
        //管辖机构
        if (Util.isNotNull(userInfo.getBelongOrganization())) {
            userInfo.setBelongOrganization(sysOrganizationMapper.selectById(userInfo.getBelongOrganization()).getOrgName());
        }
        //所在地区
        if (Util.isNotNull(userInfo.getLocation())) {
            userInfo.setLocation(getLabelNameByLabelCode(userInfo.getLocation()));
        }
        //性别
        if (Util.isNotNull(userInfo.getUserSex())) {
            userInfo.setUserSex(SexTypeEnum.getName(userInfo.getUserSex()));
        }
        //离世时间
        if (Util.isNotNull(userInfo.getDeathDate())) {
            userInfo.setDeathDate(transformDateForLoad(userInfo.getDeathDate()));
        }
        //常住人口
        if (Util.isNotNull(userInfo.getIsLongStay())) {
            if ("1".equals(userInfo.getIsLongStay())) {
                userInfo.setIsLongStay("是");
            } else if ("2".equals(userInfo.getIsLongStay())) {
                userInfo.setIsLongStay("否");
            } else {
                userInfo.setIsLongStay("");
            }
        }
        //证件号
        if (Util.isNotNull(userInfo.getUserPid())) {
            try {
                userInfo.setUserPid(AesMyUtil.Decrypt(userInfo.getUserPid()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private String getLabelNameByLabelCode(String labelCode) {
        return Util.isNull(getYsLabelByLabelCode(labelCode)) ? "" : getYsLabelByLabelCode(labelCode).getLabelName();
    }

    private YsLabel getYsLabelByLabelCode(String labelCode) {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label_code", labelCode);
        queryWrapper.eq("status", "1");
        return ysLabelMapper.selectOne(queryWrapper);
    }

    /**
     * 保存老人信息
     *
     * @param userInfo userInfo
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<Object> saveUserInfo(UserInfo userInfo) throws Exception {

        if (Util.isNotNull(getUserInfoByPid(userInfo.getUserPid()))) {
            return ResultUtil.errorMsg("此老人已存在");
        }
        //村级Level
        int villageLevel = userInfoMapper.getAreaOrgLevel(getUser().getUserNo()) + 1;

        if (Util.isNotNull(userInfo.getBelongOrganization())) {
            SysOrganization sysOrganization = getOrganizationByOrgId(userInfo.getBelongOrganization());
            if (villageLevel != Integer.parseInt(sysOrganization.getOrgLevel())) {
                return ResultUtil.errorMsg("管辖行政区,请选择村级组织");
            }
        }

        userInfo.setUserNo(Constance.getStringRandom(20));
        //转化部分字段
        transformUserInfoForSaveOrUpdate(userInfo);

        //状态 1-正常 9-删除 8-去世
        userInfo.setStatus("1");
        userInfo.setCreateTime(new Date());
        userInfoMapper.insert(userInfo);

        //保存老人的联系人
        List<UserInfoContact> userInfoContactList = userInfo.getUserInfoContactList();
        if (Util.isNotNull(userInfoContactList) && userInfoContactList.size() > 0) {
            saveUserInfoContact(userInfo.getUserNo(), userInfoContactList);
        }

        return ResultUtil.success();
    }

    /**
     * 通过证件号 查询userInfo
     */
    private UserInfo getUserInfoByPid(String userPid) throws Exception {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_pid", AesMyUtil.Encrypt(userPid));
        return userInfoMapper.selectOne(queryWrapper);
    }


    /**
     * 保存userInfo 部分字段进行转化
     */
    private void transformUserInfoForSaveOrUpdate(UserInfo userInfo) throws Exception {
        if (Util.isNull(userInfo)) {
            return;
        }
        //加密证件号 和 手机号
        if (Util.isNotNull(userInfo.getUserPid())) {
            userInfo.setUserPid(AesMyUtil.Encrypt(userInfo.getUserPid()));
        }
        if (Util.isNotNull(userInfo.getMobile())) {
            userInfo.setMobile(AesMyUtil.Encrypt(userInfo.getMobile()));
        }
        //出生日期
        if (Util.isNotNull(userInfo.getBirthDate())) {
            userInfo.setBirthDate(transformDateForSaveOrUpdate(userInfo.getBirthDate()));
        }
        //入驻时间
        if (Util.isNotNull(userInfo.getCheckInTime())) {
            userInfo.setCheckInTime(transformDateForSaveOrUpdate(userInfo.getCheckInTime()));
        }
        //离世时间
        if (Util.isNotNull(userInfo.getDeathDate())) {
            userInfo.setDeathDate(transformDateForSaveOrUpdate(userInfo.getDeathDate()));
        }
        //退休时间
        if (Util.isNotNull(userInfo.getRetireTime())) {
            userInfo.setRetireTime(transformDateForSaveOrUpdate(userInfo.getRetireTime()));
        }
        //长护险有效期
        if (Util.isNotNull(userInfo.getAssessmentValidDate())) {
            userInfo.setAssessmentValidDate(transformDateForSaveOrUpdate(userInfo.getAssessmentValidDate()));
        }
        //如果是身份证 计算年龄  不是 出生年月计算
        if (Util.isNotNull(userInfo.getCertificateType())) {
            if (CertificateTypeEnum.SFZ.getValue().equals(userInfo.getCertificateType())) {
                userInfo.setAge(CheckIdCardUtil.getAgeByCertId(userInfo.getUserPid()));
            } else {
                if (Util.isNotNull(userInfo.getBirthDate())) {
                    userInfo.setAge(Constance.getAgeByBirthDate(userInfo.getBirthDate()));
                }
            }
        }

        setLiveConditionAndBelongOrganization(userInfo);

    }

    /**
     * 设置  居住状况  和  管辖机构
     * <p>
     * 居住状况 1-人在户在 2-人在户不在 3-户在人不在     计算方式：户籍行政区 居住行政区   A有 B有 人在户在 A有B没有 户在人不在 A没有B有 人在户不在
     * 管辖机构   计算方式：户籍行政区 居住行政区   A有 B有 选择A  A有B没有 选择A  A没有B有 选择B
     *
     * @param userInfo userInfo
     */
    private void setLiveConditionAndBelongOrganization(UserInfo userInfo) {
        if (Util.isNull(userInfo)) {
            return;
        }
        if (Util.isNotNull(userInfo.getRegisterAreaOfResidence()) && Util.isNotNull(userInfo.getLiveAreaOfResidence())) {
            //居住状况
            userInfo.setLiveCondition(UserInfoLiveConditionEnum.RZHZ.getKey());
            //管辖机构
            userInfo.setBelongOrganization(userInfo.getRegisterAreaOfResidence());
        } else if (Util.isNotNull(userInfo.getRegisterAreaOfResidence()) && Util.isNull(userInfo.getLiveAreaOfResidence())) {
            //居住状况
            userInfo.setLiveCondition(UserInfoLiveConditionEnum.HZRBZ.getKey());
            //管辖机构
            userInfo.setBelongOrganization(userInfo.getRegisterAreaOfResidence());
        } else if (Util.isNull(userInfo.getRegisterAreaOfResidence()) && Util.isNotNull(userInfo.getLiveAreaOfResidence())) {
            //居住状况
            userInfo.setLiveCondition(UserInfoLiveConditionEnum.RZHBZ.getKey());
            //管辖机构
            userInfo.setBelongOrganization(userInfo.getLiveAreaOfResidence());
        }
    }


    /**
     * yyyy年xx月xx日 转换成yyyyMMdd
     */
    private String transformDateForSaveOrUpdate(String date) {
        return date.replace("年", "").replace("月", "").replace("日", "");

    }


    /**
     * 修改老人信息
     *
     * @param userInfo userInfo
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<Object> updateUserInfo(UserInfo userInfo) throws Exception {
        if (Util.isNull(userInfo.getUserNo())) {
            return ResultUtil.errorMsg("无法查询到此档案信息");
        }
        UserInfo userInfo1 = userInfoMapper.selectById(userInfo.getUserNo());

        //转化部分字段
        transformUserInfoForSaveOrUpdate(userInfo);

        //状态 1-正常 9-删除 8-去世
        userInfo.setStatus(userInfo1.getStatus());
        userInfo.setUpdateTime(new Date());
        userInfoMapper.updateById(userInfo);
        //保存老人的联系人
        List<UserInfoContact> userInfoContactList = userInfo.getUserInfoContactList();
        if (Util.isNotNull(userInfoContactList) && userInfoContactList.size() > 0) {
            saveUserInfoContact(userInfo.getUserNo(), userInfoContactList);
        }

        //判断是否需要添加历史记录   修改了管辖行政区
        if (Util.isNotNull(userInfo.getBelongOrganization()) && Util.isNotNull(userInfo1.getBelongOrganization())) {
            //管辖行政区不一致
            if (!userInfo.getBelongOrganization().equals(userInfo1.getBelongOrganization())) {

                UserInfoHistory userInfoHistory = new UserInfoHistory();
                userInfoHistory.setUserNo(userInfo.getUserNo());
                userInfoHistory.setOldBelongOrganization(userInfo1.getBelongOrganization());
                userInfoHistory.setNewBelongOrganization(userInfo.getBelongOrganization());
                userInfoHistory.setUserName(userInfo.getUserName());
                userInfoHistory.setCreateTime(new Date());
                userInfoHistoryMapper.insert(userInfoHistory);
            }
        }

        return ResultUtil.success();
    }

    /**
     * 保存老人的 联系人
     *
     * @param userNo              userInfo 主键
     * @param userInfoContactList 联系人集合
     */
    public void saveUserInfoContact(String userNo, List<UserInfoContact> userInfoContactList) {
        if (Util.isNull(userInfoContactList) || userInfoContactList.size() <= 0) {
            return;
        }
        //先删除
        QueryWrapper<UserInfoContact> userInfoContactQueryWrapper = new QueryWrapper<>();
        userInfoContactQueryWrapper.eq("user_no", userNo);
        userInfoContactMapper.delete(userInfoContactQueryWrapper);
        //后添加
        userInfoContactList.forEach(model -> {
            model.setCreateTime(new Date());
            model.setUserNo(userNo);
            if (Util.isNotNull(model.getMobile())) {
                try {
                    model.setMobile(AesMyUtil.Encrypt(model.getMobile()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            userInfoContactMapper.insert(model);
        });
    }

    /**
     * 获取老人档案 信息
     *
     * @param userNo userNo
     * @return return
     */
    public UserInfo loadUserInfoByUserNo(String userNo) throws Exception {

        UserInfo userInfo = userInfoMapper.selectById(userNo);
        //展示的时候 时间转换 yyyy年MM月dd日
        transformUserInfoForLoad(userInfo);
        //获取联系人
        userInfo.setUserInfoContactList(getUserInfoContactByUserNo(userNo));
        return userInfo;
    }

    /**
     * 查看 老人 信息
     *
     * @param userNo userNo
     * @return UserInfo
     * @throws Exception e
     */
    public UserInfo getUserInfoDetailByUserNo(String userNo) throws Exception {
        UserInfo userInfo = loadUserInfoByUserNo(userNo);

        if (Util.isNotNull(userInfo)) {
            userInfo.setDeathStatus(userInfo.getStatus());
            transformUserInfoForDetail(userInfo);
        }
        return userInfo;
    }

    /**
     * 查看 老人 信息  部分字段转换
     */
    private void transformUserInfoForDetail(UserInfo userInfo) {

        //性别
        if (Util.isNotNull(userInfo.getUserSex())) {
            userInfo.setUserSex(SexTypeEnum.getName(userInfo.getUserSex()));
        }
        //证件类型
        if (Util.isNotNull(userInfo.getCertificateType())) {
            userInfo.setCertificateType(CertificateTypeEnum.getName(userInfo.getCertificateType()));
        }
        //户籍
        if (Util.isNotNull(userInfo.getHouseholdRegister())) {
            userInfo.setHouseholdRegister(getLabelName(userInfo.getHouseholdRegister()));
        }
        //民族
        if (Util.isNotNull(userInfo.getNation())) {
            userInfo.setNation(getLabelName(userInfo.getNation()));
        }
        //所在地区
        if (Util.isNotNull(userInfo.getLocation())) {
            userInfo.setLocation(getLabelName(userInfo.getLocation()));
        }
        //婚姻状况
        if (Util.isNotNull(userInfo.getMarriage())) {
            userInfo.setMarriage(getLabelName(userInfo.getMarriage()));
        }
        //户籍行政区
        if (Util.isNotNull(userInfo.getRegisterAreaOfResidence())) {
            //要查询组织架构
            userInfo.setRegisterAreaOfResidence(getOrganizationByOrgId(userInfo.getRegisterAreaOfResidence()).getOrgName());
        }
        //居住行政区
        if (Util.isNotNull(userInfo.getLiveAreaOfResidence())) {
            //要查询组织架构
            userInfo.setLiveAreaOfResidence(getOrganizationByOrgId(userInfo.getLiveAreaOfResidence()).getOrgName());
        }
        //社保类型
        if (Util.isNotNull(userInfo.getSocialSecurityType())) {
            userInfo.setSocialSecurityType(getLabelName(userInfo.getSocialSecurityType()));
        }
        //文化程度
        if (Util.isNotNull(userInfo.getDegreeOfEducation())) {
            userInfo.setDegreeOfEducation(getLabelName(userInfo.getDegreeOfEducation()));
        }
        //政治面貌
        if (Util.isNotNull(userInfo.getPolitical())) {
            userInfo.setPolitical(getLabelName(userInfo.getPolitical()));
        }
        //退休工资
        if (Util.isNotNull(userInfo.getRetireSalary())) {
            userInfo.setRetireSalary(userInfo.getRetireSalary() + "元/月");
        }
        //所属管辖机构
        if (Util.isNotNull(userInfo.getBelongOrganization())) {
            //要查询组织架构
            userInfo.setBelongOrganization(getOrganizationByOrgId(userInfo.getBelongOrganization()).getOrgName());
        }
        //居住状态 人在户在 户在人不在 人在户不在
        if (Util.isNotNull(userInfo.getLiveCondition())) {
            userInfo.setLiveCondition(UserInfoLiveConditionEnum.getName(userInfo.getLiveCondition()));
        }
        //当前状态
        if (Util.isNotNull(userInfo.getStatus())) {
            userInfo.setStatus(UserInfoStatusEnum.getName(userInfo.getStatus()));
        }
        //养老状况
        if (Util.isNotNull(userInfo.getPensionStatus())) {
            userInfo.setPensionStatus(getLabelName(userInfo.getPensionStatus()));
        }
        //照顾人群
        if (Util.isNotNull(userInfo.getCareCrowd())) {
            userInfo.setCareCrowd(getLabelName(userInfo.getCareCrowd()));
        }
        //居家情况
        if (Util.isNotNull(userInfo.getLiveHomeStatus())) {
            userInfo.setLiveHomeStatus(getLabelName(userInfo.getLiveHomeStatus()));
        }
        //持证情况
        if (Util.isNotNull(userInfo.getHoldCertificateStatus())) {
            userInfo.setHoldCertificateStatus(getLabelName(userInfo.getHoldCertificateStatus()));
        }
        //认知情况
        if (Util.isNotNull(userInfo.getCognitionStatus())) {
            userInfo.setCognitionStatus(getLabelName(userInfo.getCognitionStatus()));
        }
        //涉外情况
        if (Util.isNotNull(userInfo.getForeignIdentityStatus())) {
            userInfo.setForeignIdentityStatus(getLabelName(userInfo.getForeignIdentityStatus()));
        }
        //安全情况
        if (Util.isNotNull(userInfo.getSafeStatus())) {
            userInfo.setSafeStatus(getLabelName(userInfo.getSafeStatus()));
        }
        //健康情况
        if (Util.isNotNull(userInfo.getHealthStatus())) {
            userInfo.setHealthStatus(getLabelName(userInfo.getHealthStatus()));
        }
        //其他情况
        if (Util.isNotNull(userInfo.getOtherStatus())) {
            userInfo.setOtherStatus(getLabelName(userInfo.getOtherStatus()));
        }
        //老人的联系人
        if (Util.isNotNull(userInfo.getUserInfoContactList()) && userInfo.getUserInfoContactList().size() > 0) {
            userInfo.getUserInfoContactList().forEach(model -> model.setRelationship(getLabelName(model.getRelationship())));
        }
        //常住人口 1-是 2否
        if (Util.isNotNull(userInfo.getIsLongStay())) {
            userInfo.setIsLongStay("1".equalsIgnoreCase(userInfo.getIsLongStay()) ? "是" : "否");
        }


    }


    /**
     * 页面展示  时间 手机号 证件号 转换
     */
    private void transformUserInfoForLoad(UserInfo userInfo) throws Exception {
        //出生日期
        if (Util.isNotNull(userInfo.getBirthDate())) {
            userInfo.setBirthDate(transformDateForLoad(userInfo.getBirthDate()));
        }
        //入驻时间
        if (Util.isNotNull(userInfo.getCheckInTime())) {
            userInfo.setCheckInTime(transformDateForLoad(userInfo.getCheckInTime()));
        }
        //离世时间
        if (Util.isNotNull(userInfo.getDeathDate())) {
            userInfo.setDeathDate(transformDateForLoad(userInfo.getDeathDate()));
        }
        //退休时间
        if (Util.isNotNull(userInfo.getRetireTime())) {
            userInfo.setRetireTime(transformDateForLoad(userInfo.getRetireTime()));
        }
        //长护险有效期
        if (Util.isNotNull(userInfo.getAssessmentValidDate())) {
            userInfo.setAssessmentValidDate(transformDateForLoad(userInfo.getAssessmentValidDate()));
        }
        //手机号
        if (Util.isNotNull(userInfo.getMobile())) {
            userInfo.setMobile(AesMyUtil.Decrypt(userInfo.getMobile()));
        }
        //证件号
        if (Util.isNotNull(userInfo.getUserPid())) {
            userInfo.setUserPid(AesMyUtil.Decrypt(userInfo.getUserPid()));
        }
        //户籍行政区域 name
        if (Util.isNotNull(userInfo.getRegisterAreaOfResidence())) {

            userInfo.setRegisterAreaOfResidenceOrgName(getOrganizationByOrgId(userInfo.getRegisterAreaOfResidence()).getOrgName());
        }
        //居住行政区域 name
        if (Util.isNotNull(userInfo.getLiveAreaOfResidence())) {
            userInfo.setLiveAreaOfResidenceOrgName(getOrganizationByOrgId(userInfo.getLiveAreaOfResidence()).getOrgName());
        }
        //管辖行政区
        if (Util.isNotNull(userInfo.getBelongOrganization())) {
            userInfo.setBelongOrganizationOrgName(getOrganizationByOrgId(userInfo.getBelongOrganization()).getOrgName());
        }
    }

    /**
     * 给页面展示的时候用
     */
    private String transformDateForLoad(String date) {
        if (date.length() < 8) {
            return date;
        }
        return date.substring(0, 4) + "年" + date.substring(4, 6) + "月" + date.substring(6, 8) + "日";
    }

    private String transformDateForElderly(String date) {
        return date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
    }


    /**
     * 通过userNo 获取老人的联系人
     */
    public List<UserInfoContact> getUserInfoContactByUserNo(String userNo) {
        QueryWrapper<UserInfoContact> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_no", userNo);
        List<UserInfoContact> userInfoContacts = userInfoContactMapper.selectList(queryWrapper);
        userInfoContacts.forEach(model -> {
            if (Util.isNotNull(model.getMobile())) {
                try {
                    model.setMobile(AesMyUtil.Decrypt(model.getMobile()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return userInfoContacts;
    }


    /**
     * 删除联系人
     *
     * @param contactNo 联系人No
     * @return Result
     */
    public Result<Object> deleteUserInfoContact(String contactNo) {
        userInfoContactMapper.deleteById(contactNo);
        return ResultUtil.success();
    }


    /**
     * 删除档案
     *
     * @param userNo userNo
     * @return Result
     */
    public Result<Object> deleteUserInfoByUserNo(String userNo) {
        UserInfo userInfo = userInfoMapper.selectById(userNo);
        if (Util.isNull(userInfo)) {
            return ResultUtil.errorMsg("无法查询到此档案");
        }
        //删除
//        userInfo.setStatus("9");
        userInfoMapper.deleteById(userInfo);
        return ResultUtil.success();
    }

    /**
     * 老人 离世处理
     */
    public Result<Object> dealDeathUserInfoByUserNo(UserInfo user) {
        UserInfo userInfo = userInfoMapper.selectById(user.getUserNo());
        if (Util.isNull(userInfo)) {
            return ResultUtil.errorMsg("无法查询到此档案");
        }
        userInfo.setDeathDate(transformDateForSaveOrUpdate(user.getDeathDate()));
        userInfo.setDeathReason(user.getDeathReason());
        //状态 1-正常 8-去世  9-删除
        userInfo.setStatus("8");
        userInfoMapper.updateById(userInfo);
        return ResultUtil.success();
    }


    /**
     * 获取Excel导入记录列表
     *
     * @return Result
     */
    public Result<Object> getReportRecordList(ReportRecordPageVO vo) {
        QueryWrapper<ReportRecord> queryWrapper = new QueryWrapper<>();
        if (Util.isNotNull(vo.getOrgId())) {
            queryWrapper.eq("org_id", vo.getOrgId());
        }
        if (Util.isNotNull(getUser())) {
            queryWrapper.eq("sys_user_no", getUser().getUserNo());
        }

        queryWrapper.orderByDesc("create_time");
        IPage<ReportRecord> recordPage = reportRecordMapper.selectPage(new Page<>(vo.getCurrentPage(), vo.getPageSize()), queryWrapper);
        List<ReportRecord> recordList = recordPage.getRecords();
        //转化数据
        transformReportRecordList(recordList);
        return ResultUtil.getPageDataSuccess(new PageDo<>(recordPage.getCurrent(), recordPage.getSize(), Integer.parseInt(recordPage.getTotal() + ""), recordList));
    }

    private void transformReportRecordList(List<ReportRecord> recordList) {
        recordList.forEach(model -> {
            model.setFormatCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.ofInstant(model.getCreateTime().toInstant(), ZoneId.systemDefault())));
            model.setFormatReportTypeName("老人信息表");
            //获取成功或失败的数量
            model.setSuccessCount(getSuccessOrFailCount(model.getId(), 1));
            model.setFailCount(getSuccessOrFailCount(model.getId(), 9));

            //操作人员姓名
            if (Util.isNotNull(model.getSysUserNo())) {
                model.setSysName(sysUserMapper.selectById(model.getSysUserNo()).getUserName());
            }

            //机构名称
            if (Util.isNotNull(model.getOrgId())) {
                model.setFormatOrgName(sysOrganizationMapper.selectById(model.getOrgId()).getOrgName());
            }
        });
    }


    /**
     * @param reportId 关联报表记录id(report_record)
     * @param state    1：成功 9：失败
     * @return count
     */
    private Integer getSuccessOrFailCount(Integer reportId, Integer state) {
        QueryWrapper<ReportRecordLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_record_id", reportId);
        queryWrapper.eq("state", state);
        return reportRecordLogMapper.selectCount(queryWrapper);
    }


    /**
     * 导入老人报表
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<Object> importReport(ReportRecordVO reportRecordVO, SysUser sysUser) throws Exception {

        if (Util.isNull(reportRecordVO.getAddOrCover())) {
            return ResultUtil.errorMsg("导入报表缺少参数");
        } else if (Util.isNull(reportRecordVO.getFile())) {
            return ResultUtil.errorMsg("缺少文件");
        }
        //导入类型 1-老人档案报表
        reportRecordVO.setReportType(1);
        return importReportOfUserInfo(reportRecordVO, sysUser);
    }

    /**
     * 导入老人报表 -具体实现
     *
     * @param reportRecordVO reportRecordVO
     */
    private Result<Object> importReportOfUserInfo(ReportRecordVO reportRecordVO, SysUser sysUser) throws Exception {

        //证件类型
        List<YsLabel> certificateList = getMsLabelList(LabelTypeEnum.ZJLX.getKey());
        //民族
        List<YsLabel> nationList = getMsLabelList(LabelTypeEnum.MZ.getKey());
        //婚姻状况
        List<YsLabel> marriageList = getMsLabelList(LabelTypeEnum.HYQK.getKey());
        //政治面貌
        List<YsLabel> politicalList = getMsLabelList(LabelTypeEnum.ZZMM.getKey());

        //所在地区
        List<YsLabel> locationList = getMsLabelList(LabelTypeEnum.SZDQ.getKey());
        //社保类型
        List<YsLabel> socialSecurityList = getMsLabelList(LabelTypeEnum.SBLX.getKey());
        //文化程度
        List<YsLabel> educationList = getMsLabelList(LabelTypeEnum.WHCD.getKey());
        //养老状况
        List<YsLabel> pensionStatusList = getMsLabelList(LabelTypeEnum.YLZK.getKey());
        //居家状况
        List<YsLabel> liveHomeStatusList = getMsLabelList(LabelTypeEnum.JJQK.getKey());
        //照顾人群
        List<YsLabel> careCrowdList = getMsLabelList(LabelTypeEnum.ZGRQ.getKey());
        //与老人关系
        List<YsLabel> relationShipList = getMsLabelList(LabelTypeEnum.YLRGX.getKey());
        //所有组织架构
        List<SysOrganization> allSysOrganization = getAllSysOrganization();
        //所有养老机构
        List<SysOrganization> allPensionList = getPensionOrgList();


        //获取所有身份证判断是否重复
        List<String> userPidList = getUserPidList();

        //读取excel中的数据
        List<UserInfoExcel> excelUserInfoList = readExcel(reportRecordVO);

        if (excelUserInfoList.size() <= 0) {
            return ResultUtil.errorMsg("请不要导入空文件");
        }
        if (!isTrueHead) {
            return ResultUtil.errorMsg("表头与模板不一致,请上传正确文件");
        }

        //设置序列号
        setSort(excelUserInfoList);
        //获取 excel中的身份证
        List<String> idCards = new ArrayList<>();
        excelUserInfoList.forEach(excelUserInfo -> {
            try {
                if (Util.isNotNull(excelUserInfo.getUserPid())) {
                    idCards.add(AesMyUtil.Encrypt(excelUserInfo.getUserPid()));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
        });

        //保存的userInfo
        List<UserInfo> saveMsUserInfoList = new ArrayList<>();
        //成功
        List<ReportRecordLog> saveSuccessLogList = new ArrayList<>();
        //失败
        List<ReportRecordLog> saveFailLogList = new ArrayList<>();

        //校验数据 和 数据处理
        excelUserInfoList.forEach(excelUserInfo -> {

            //数据校验
            String errorMsg = null;
            try {
                errorMsg = excelUserInfoDataCheck(excelUserInfo, userPidList, reportRecordVO.getAddOrCover(), allSysOrganization);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //判断身份证号是否重复
            int count = Collections.frequency(idCards, excelUserInfo.getUserPid());
            if (count > 1) {
                if (Util.isNotNull(errorMsg)) {
                    errorMsg += (",报表中身份证号重复出现");
                } else {
                    errorMsg += ("报表中身份证号重复出现");
                }
            }

            //*********** 将数据分别放入不同的集合中 **************
            //errorMsg为空 说明数据校验通过
            if (Util.isNull(errorMsg)) {
                ReportRecordLog successLog = getReportRecordLog(excelUserInfo, errorMsg, 1);
                saveSuccessLogList.add(successLog);
                // 如果保存userInfo    数据处理
                transformForDataExcelUserInfo(excelUserInfo, certificateList, nationList, marriageList, politicalList, locationList
                        , socialSecurityList, educationList, pensionStatusList, liveHomeStatusList, careCrowdList
                        , allSysOrganization, allPensionList);
                UserInfo userInfo = getUserInfo(excelUserInfo);
                saveMsUserInfoList.add(userInfo);
            } else {
                //错误日志  state //1-成功 9-失败
                ReportRecordLog failLog = getReportRecordLog(excelUserInfo, errorMsg, 9);
                saveFailLogList.add(failLog);
            }
        });

        //***********保存userInfo , report_record_log, report_record **************
        String importResult = "成功导入" + saveSuccessLogList.size() + "数据,失败" + saveFailLogList.size() + "笔";
        //保存报表记录
        ReportRecord msReportRecord = getMsReportRecord(reportRecordVO, importResult, sysUser);
        reportRecordMapper.insert(msReportRecord);
        //放入报表的id
        saveSuccessLogList.forEach(successMsReportLog -> successMsReportLog.setReportRecordId(msReportRecord.getId()));
        saveFailLogList.forEach(failMsReportLog -> failMsReportLog.setReportRecordId(msReportRecord.getId()));

        //保存老人 和老人的联系人
        saveUserInfoOfExcel(saveMsUserInfoList, userPidList, reportRecordVO.getAddOrCover(), relationShipList, reportRecordVO.getOrgId());
        //保存成功和错误日志
        saveSuccessLogList.forEach(successMsReportLog -> reportRecordLogMapper.insert(successMsReportLog));
        saveFailLogList.forEach(failMsReportLog -> reportRecordLogMapper.insert(failMsReportLog));

        return ResultUtil.success(200, importResult);

    }


    //****************************************************************************************************************//


    /**
     * 读取数据
     */
    private List<UserInfoExcel> readExcel(ReportRecordVO reportRecordVO) throws Exception {
        List<UserInfoExcel> excelUserInfoList = new ArrayList<>();
        EasyExcel.read(reportRecordVO.getFile().getInputStream(), UserInfoExcel.class, new AnalysisEventListener<UserInfoExcel>() {
            @Override
            public void invoke(UserInfoExcel userInfoExcel, AnalysisContext analysisContext) {
                excelUserInfoList.add(userInfoExcel);
            }

            @Override
            public void invokeHeadMap(Map headMap, AnalysisContext context) {
                isTrueHead = isExcelHead(JSONObject.fromObject(JSON.toJSONString(headMap)));
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
        }).sheet().doRead();
        return excelUserInfoList;
    }


    /**
     * 报表记录对象
     */
    private ReportRecord getMsReportRecord(ReportRecordVO reportRecordVO, String importResult, SysUser sysUser) {
        ReportRecord msReportRecord = new ReportRecord();
        msReportRecord.setReportName(reportRecordVO.getFile().getOriginalFilename());
        msReportRecord.setImportResult(importResult);
        msReportRecord.setReportType(reportRecordVO.getReportType());
        //操作人员
        if (Util.isNotNull(sysUser.getUserNo())) {
            msReportRecord.setSysUserNo(sysUser.getUserNo());
        }
        //小区编号
        if (Util.isNotNull(reportRecordVO.getOrgId())) {
            msReportRecord.setOrgId(reportRecordVO.getOrgId());
        }
        msReportRecord.setCreateTime(new Date());
        return msReportRecord;
    }

    /**
     * 保存 Excel中的 老年居民
     *
     * @param saveMsUserInfoList saveMsUserInfoList
     * @param userPidList        身份证号List
     * @param addOrCover         增加或者覆盖 1-增加 2-覆盖
     * @param relationShipList   与老人关系
     */
    private void saveUserInfoOfExcel(List<UserInfo> saveMsUserInfoList, List<String> userPidList, Integer addOrCover
            , List<YsLabel> relationShipList, String orgId) {
        int addNum = 1;
        int coverNum = 2;

        saveMsUserInfoList.forEach(userInfo -> {
            if (Util.isNotNull(orgId)) {
                userInfo.setBelongOrganization(orgId);
            }
//            System.out.println(userInfo.getUserName());
//            System.out.println(userInfo.getOccupation());
            //增加
            if (addNum == addOrCover) {
                userInfoMapper.insert(userInfo);
            } else if (coverNum == addOrCover) {
                try {
                    if (userPidList.contains(AesMyUtil.Decrypt(userInfo.getUserPid()))) {
                        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
                        userInfoQueryWrapper.eq("USER_PID", userInfo.getUserPid());
                        UserInfo existUserInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
                        userInfo.setUserNo(existUserInfo.getUserNo());
                        userInfoMapper.updateById(userInfo);

                        //判断是否需要添加历史记录   修改了管辖行政区
                        if (Util.isNotNull(userInfo.getBelongOrganization()) && Util.isNotNull(existUserInfo.getBelongOrganization())) {
                            //管辖行政区不一致
                            if (!userInfo.getBelongOrganization().equals(existUserInfo.getBelongOrganization())) {
                                UserInfoHistory userInfoHistory = new UserInfoHistory();
                                userInfoHistory.setUserNo(userInfo.getUserNo());
                                userInfoHistory.setOldBelongOrganization(existUserInfo.getBelongOrganization());
                                userInfoHistory.setNewBelongOrganization(userInfo.getBelongOrganization());
                                userInfoHistory.setUserName(userInfo.getUserName());
                                userInfoHistory.setCreateTime(new Date());
                                userInfoHistoryMapper.insert(userInfoHistory);
                            }
                        }
                    } else {
                        userInfoMapper.insert(userInfo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            List<UserInfoContact> userInfoContacts = userInfo.getUserInfoContactList();
            //紧急联系人
            if (Util.isNotNull(userInfoContacts) && userInfoContacts.size() > 0) {
                //与老人关系 转化labelCode  手机号加密
                userInfoContacts.forEach(userInfoContact -> userInfoContact.setRelationship(getLabelCodes(relationShipList, userInfoContact.getRelationship())));

                //保存紧急联系人
                saveUserInfoContact(userInfo.getUserNo(), userInfo.getUserInfoContactList());
            }
        });
    }


    /**
     * 导入userInfo 报表数据校验
     *
     * @param excelUserInfo excelUserInfo
     * @param userPidList   身份号List 判断是否重复
     * @param addOrCover    增加或者覆盖 1-增加 2-覆盖
     * @return String 错误信息
     */
    private String excelUserInfoDataCheck(UserInfoExcel excelUserInfo, List<String> userPidList
            , Integer addOrCover, List<SysOrganization> allSysOrganization) throws Exception {

        StringBuilder errorMsg = new StringBuilder();
        //姓名
        int nameMaxSize = 20;
        if (Util.isNull(excelUserInfo.getUserName())) {
            errorMsg.append("姓名不能为空,");
        } else if (excelUserInfo.getUserName().length() > nameMaxSize) {
            errorMsg.append("姓名输入过长(长度超过20位字符),");
            //姓名过长截取 否则记录表无法保存
            excelUserInfo.setUserName(excelUserInfo.getUserName().substring(0, 15) + "...");
        }

        //验证证件类型 和 证件号
        checkCertificateTypeAndUserPid(errorMsg, excelUserInfo, userPidList, addOrCover);

        //验证各种日期格式
        judgeAllDateFormats(errorMsg, excelUserInfo);

        int limitLength = 100;
        //户籍地址
        if (Util.isNull(excelUserInfo.getRegisterAddress())) {
            errorMsg.append("户籍地址不能为空,");

        } else if (Util.isNotNull(excelUserInfo.getRegisterAddress())) {
            if (excelUserInfo.getRegisterAddress().length() > limitLength) {
                errorMsg.append("户籍地址过长(不能超过100位字符),");
                excelUserInfo.setRegisterAddress(excelUserInfo.getRegisterAddress().substring(0, 90) + "...");
            }
        }
        //居住地址
        if (Util.isNull(excelUserInfo.getLiveAddress())) {
            errorMsg.append("居住地址不能为空,");
        } else if (Util.isNotNull(excelUserInfo.getLiveAddress())) {
            if (excelUserInfo.getLiveAddress().length() > limitLength) {
                errorMsg.append("现居住地址过长(不能超过100位字符),");
                excelUserInfo.setLiveAddress(excelUserInfo.getLiveAddress().substring(0, 90) + "...");
            }
        }

        //户籍所在地区(根据下拉框选择)
        if (Util.isNull(excelUserInfo.getLocation())) {
            errorMsg.append("户籍所在地区不能为空,");
        }

        //常住人口(根据下拉框选择)
        if (Util.isNull(excelUserInfo.getIsLongStay())) {
            errorMsg.append("常住人口不能为空,");
        }

        //手机号码
        int telSize = 20;
        if (Util.isNotNull(excelUserInfo.getMobile())) {
            if (!CheckIdCardUtil.isChinaPhoneLegal(excelUserInfo.getMobile())) {
                errorMsg.append("手机号码输入有误,");
            }
            if (excelUserInfo.getMobile().length() > telSize) {
                excelUserInfo.setMobile(excelUserInfo.getMobile().substring(0, 15) + "...");
            }
            //手机号加密
            excelUserInfo.setMobile(AesMyUtil.Encrypt(excelUserInfo.getMobile()));
        }
        //固定电话
        if (Util.isNotNull(excelUserInfo.getTel())) {
            if (excelUserInfo.getTel().length() > telSize) {
                errorMsg.append("固定电话输入过长,");
                excelUserInfo.setTel(excelUserInfo.getTel().substring(0, 15) + "...");
            }
        }
        //职业
        if (Util.isNotNull(excelUserInfo.getOccupation())) {
            if (excelUserInfo.getOccupation().length() > limitLength) {
                errorMsg.append("职业输入过长(不能超过100位字符),");
                excelUserInfo.setOccupation(excelUserInfo.getOccupation().substring(0, 90) + "...");
            }
        }
        //退休工资
        if (Util.isNotNull(excelUserInfo.getRetireSalary())) {
            if (!Util.isSalaryNumber(excelUserInfo.getRetireSalary())) {
                errorMsg.append("退休工资输入有误,");
            }
        }
        //退休单位
        if (Util.isNotNull(excelUserInfo.getRetireCompany())) {
            if (excelUserInfo.getRetireCompany().length() > limitLength) {
                errorMsg.append("退休单位输入过长(不能超过100位字符),");
                excelUserInfo.setRetireCompany(excelUserInfo.getRetireCompany().substring(0, 90) + "...");
            }
        }
        //健康描述
        int healthLimitLength = 300;
        if (Util.isNotNull(excelUserInfo.getHealthDescription())) {
            if (excelUserInfo.getHealthDescription().length() > healthLimitLength) {
                errorMsg.append("健康描述输入过长(不能超过300位字符),");
                excelUserInfo.setHealthDescription(excelUserInfo.getHealthDescription().substring(0, 290) + "...");
            }
        }

        //养老状况  如果养老状况选择‘养老机构养老’，养老机构必填写，而且必须是安亭镇辖区内的养老院，或者'其他养老院'
        String pensionStatusStr = "养老机构养老";
        if (Util.isNull(excelUserInfo.getPensionStatus())) {
            errorMsg.append("养老状况不能为空,");
        } else if (pensionStatusStr.equals(excelUserInfo.getPensionStatus())) {
            if (Util.isNull(excelUserInfo.getPensionInstitutions())) {
                errorMsg.append("养老状况为养老机构养老时 养老机构不能为空,");
            }
            if (Util.isNull(excelUserInfo.getCheckInTime())) {
                errorMsg.append("养老状况为养老机构养老时 入驻时间不能为空,");
            }
        }
        //长护险等级
        if (Util.isNull(excelUserInfo.getAssessmentLevel()) && Util.isNotNull(excelUserInfo.getAssessmentValidDate())) {
            errorMsg.append("长护险等级和长护险有效期 必须一起填写,");
        }
        if (Util.isNotNull(excelUserInfo.getAssessmentLevel()) && Util.isNull(excelUserInfo.getAssessmentValidDate())) {
            errorMsg.append("长护险等级和长护险有效期 必须一起填写,");
        }
        //管辖行政区域
        int belongOrganizationLimitLength = 50;
        if (Util.isNull(excelUserInfo.getBelongOrganization())) {
            errorMsg.append("管辖行政区域不能为空,");
        } else {
            if (excelUserInfo.getBelongOrganization().length() >= belongOrganizationLimitLength) {
                errorMsg.append("管辖行政区域长度过长,");
                excelUserInfo.setBelongOrganization(excelUserInfo.getBelongOrganization().substring(0, 40) + "......");
            }
            String orgId = getOrgIdByMatchingOrgName(allSysOrganization, excelUserInfo.getBelongOrganization());
            if (Util.isNull(orgId)) {
                errorMsg.append("管辖行政区域匹配失败,");
            } else if (!isTerminalNodeOrg(orgId)) {
                errorMsg.append("管辖行政区域需为村级组织,");
            }
        }

        //第一联系人
        int limitName = 20;
        if (Util.isNotNull(excelUserInfo.getOneContractName())) {
            if (excelUserInfo.getOneContractName().length() >= limitName) {
                errorMsg.append("第一联系人姓名长度过长,");
                excelUserInfo.setOneContractName(excelUserInfo.getOneContractName().substring(0, 15) + "...");
            }
        }
        //第二联系人
        if (Util.isNotNull(excelUserInfo.getTwoContractName())) {
            if (excelUserInfo.getTwoContractName().length() >= limitName) {
                errorMsg.append("第二联系人姓名长度过长,");
                excelUserInfo.setTwoContractName(excelUserInfo.getTwoContractName().substring(0, 15) + "...");
            }
        }

        //紧急联系人
        List<UserInfoContact> userInfoContacts = getEmergencyContact(excelUserInfo);
        excelUserInfo.setUserInfoContactList(userInfoContacts);


        return Util.isNull(errorMsg.toString()) ? "" : errorMsg.toString().substring(0, errorMsg.toString().length() - 1);
    }


    /**
     * 判断所有日期格式是否正确
     *
     * @param errorMsg      errorMsg
     * @param excelUserInfo excelUserInfo
     */
    private void judgeAllDateFormats(StringBuilder errorMsg, UserInfoExcel excelUserInfo) {
        //如果不是身份证类型  就判断生日的日期格式
        if (!CertificateTypeEnum.SFZ.getValue().equals(excelUserInfo.getCertificateType())) {
            if (Util.isNotNull(excelUserInfo.getBirthDate())) {
                if (isTrueDate(excelUserInfo.getBirthDate())) {
                    errorMsg.append("出生日期格式有误,");
                }
            }
        }

        //退休时间
        if (Util.isNotNull(excelUserInfo.getRetireTime())) {
            if (isTrueDate(excelUserInfo.getRetireTime())) {
                errorMsg.append("退休时间格式有误,");
            }
        }
        //入驻时间
        if (Util.isNotNull(excelUserInfo.getCheckInTime())) {
            if (isTrueDate(excelUserInfo.getCheckInTime())) {
                errorMsg.append("入驻时间格式有误,");
            }
        }
        //长护险有效期
        if (Util.isNotNull(excelUserInfo.getAssessmentValidDate())) {
            if (isTrueDate(excelUserInfo.getAssessmentValidDate())) {
                errorMsg.append("长护险有效期格式有误,");
            }
        }
    }


    /**
     * 判断日期是否正确
     */
    private boolean isTrueDate(String date) {
        if (date.length() != 10) {
            return true;
        }
        //判断横线
        String line = date.substring(date.length() - 3, date.length() - 2);
        String line2 = date.substring(4, 5);
        return !"-".equals(line) || !"-".equals(line2);
    }


    /**
     * 判断 组织名称是否跟数据库的匹配
     *
     * @param allSysOrganization allSysOrganization
     * @param orgName            orgName
     * @return boolean
     */
    private String getOrgIdByMatchingOrgName(List<SysOrganization> allSysOrganization, String orgName) {
        String orgId = "";
        if (Util.isNull(orgName)) {
            return orgId;
        }
        for (SysOrganization org : allSysOrganization) {
            if (org.getOrgName().equals(orgName)) {
                orgId = String.valueOf(org.getOrgId());
                break;
            }
        }
        return orgId;
    }


    /**
     * 从Excel中 获取紧急联系人
     *
     * @param excelUserInfo excelUserInfo
     */
    private List<UserInfoContact> getEmergencyContact(UserInfoExcel excelUserInfo) {
        //第一联系人
        UserInfoContact oneContact = getUserInfoContactOfExcel(excelUserInfo.getOneContractName(), excelUserInfo.getOneRelationship(), excelUserInfo.getOneTel(), excelUserInfo.getOneAddress(), excelUserInfo.getOneMobile());
        //第二联系人
        UserInfoContact twoContact = getUserInfoContactOfExcel(excelUserInfo.getTwoContractName(), excelUserInfo.getTwoRelationship(), excelUserInfo.getTwoTel(), excelUserInfo.getTwoAddress(), excelUserInfo.getTwoMobile());

        List<UserInfoContact> userInfoContacts = new ArrayList<>();
        if (Util.isNotNull(oneContact)) {
            userInfoContacts.add(oneContact);
        }
        if (Util.isNotNull(twoContact)) {
            userInfoContacts.add(twoContact);
        }

        return userInfoContacts;
    }


    /**
     * @param contactName  联系人姓名
     * @param relationShip 联系人与老人关系
     * @param tel          固定电话
     * @param address      详细地址
     * @param mobile       手机电话
     */
    private UserInfoContact getUserInfoContactOfExcel(String contactName, String relationShip, String tel, String address, String mobile) {
        if (Util.isNotNull(contactName) && Util.isNotNull(relationShip)) {
            UserInfoContact userInfoContact = new UserInfoContact();
            userInfoContact.setContactName(contactName);
            userInfoContact.setRelationship(relationShip);
            userInfoContact.setTel(tel);
            userInfoContact.setAddress(address);
            userInfoContact.setMobile(mobile);
            userInfoContact.setCreateTime(new Date());
            return userInfoContact;
        } else {
            return null;
        }
    }


    /**
     * 验证证件类型 和证件号
     */
    private void checkCertificateTypeAndUserPid(StringBuilder errorMsg, UserInfoExcel excelUserInfo
            , List<String> userPidList, Integer addOrCover) throws Exception {

        //证件类型
        if (Util.isNull(excelUserInfo.getCertificateType())) {
            errorMsg.append("证件类型不能为空,");
        } else if (CertificateTypeEnum.SFZ.getValue().equals(excelUserInfo.getCertificateType()) && Util.isNotNull(excelUserInfo.getUserPid())) {
            //如果是身份证进行身份证验证
            if (!CheckIdCardUtil.check(excelUserInfo.getUserPid())) {
                errorMsg.append("身份证号输入有误,");
            } else {
                //  如果是身份证正确 获取生日 和性别
                excelUserInfo.setBirthDate(CheckIdCardUtil.getBirthDayPart(excelUserInfo.getUserPid()));
                excelUserInfo.setUserSex(CheckIdCardUtil.getSexByIdentityNumber(excelUserInfo.getUserPid()));
                //年龄
                excelUserInfo.setAge(CheckIdCardUtil.getAgeByCertId(excelUserInfo.getUserPid()));
            }
            //增加的时候判断身份证号是否重复
            if (addOrCover == 1) {
                if (userPidList.contains(excelUserInfo.getUserPid())) {
                    errorMsg.append("身份证号已存在,");
                }
            }
        } else if (Util.isNull(CertificateTypeEnum.getEnumKey(excelUserInfo.getCertificateType()))) {
            errorMsg.append("证件类型匹配不上,");
        } else if (!CertificateTypeEnum.SFZ.getValue().equals(excelUserInfo.getCertificateType())) {
            //如果证件类型!=身份证 出生日期不能为空  性别不能为空
            //出生日期
            int birthSize = 10;
            if (Util.isNull(excelUserInfo.getBirthDate())) {
                errorMsg.append("证件类型不是身份证 出生日期不能为空,");
            } else if (excelUserInfo.getBirthDate().length() != birthSize) {
                errorMsg.append("出生日期格式有误,");
                excelUserInfo.setBirthDate(excelUserInfo.getBirthDate().substring(0, excelUserInfo.getBirthDate().length() - 5) + "...");
            }
            //性别
            if (Util.isNotNull(excelUserInfo.getUserSex())) {
                errorMsg.append("证件类型不是身份证 性别不能为空,");
            }
        }

        //证件号
        int pidMax = 20;
        if (Util.isNull(excelUserInfo.getUserPid())) {
            errorMsg.append("证件号不能为空,");
        } else if (excelUserInfo.getUserPid().length() > pidMax) {
            errorMsg.append("证件号过长,");
            //证件号
            excelUserInfo.setUserPid(AesMyUtil.Encrypt(excelUserInfo.getUserPid().substring(0, 15) + "..."));
        } else {
            excelUserInfo.setUserPid(AesMyUtil.Encrypt(excelUserInfo.getUserPid()));
        }


    }

    /**
     * 数据处理
     *
     * @param excelUserInfo      excelUserInfo
     * @param certificateList    证件类型
     * @param nationList         民族
     * @param marriageList       婚姻状况
     * @param politicalList      政治面貌
     * @param locationList       所在地区
     * @param socialSecurityList 社保类型
     * @param educationList      文化程度
     * @param pensionStatusList  养老状况
     * @param liveHomeStatusList 居家状况
     * @param careCrowdList      照顾人群
     * @param allPensionList     养老机构
     */
    private void transformForDataExcelUserInfo(UserInfoExcel excelUserInfo, List<YsLabel> certificateList, List<YsLabel> nationList
            , List<YsLabel> marriageList, List<YsLabel> politicalList, List<YsLabel> locationList
            , List<YsLabel> socialSecurityList, List<YsLabel> educationList, List<YsLabel> pensionStatusList, List<YsLabel> liveHomeStatusList
            , List<YsLabel> careCrowdList, List<SysOrganization> allSysOrganization, List<SysOrganization> allPensionList) {

        //证件类型
        if (Util.isNotNull(excelUserInfo.getCertificateType())) {
            String certificateType = getLabelCodes(certificateList, excelUserInfo.getCertificateType());
            excelUserInfo.setCertificateType(Util.isNull(certificateType) ? "" : certificateType);
        }
        //民族
        if (Util.isNotNull(excelUserInfo.getNation())) {
            String getLabelCodes = getLabelCodes(nationList, excelUserInfo.getNation());
            excelUserInfo.setNation(Util.isNull(getLabelCodes) ? "" : getLabelCodes);
        }
        //婚姻状况
        if (Util.isNotNull(excelUserInfo.getMarriage())) {
            String marriageType = getLabelCodes(marriageList, excelUserInfo.getMarriage());
            excelUserInfo.setMarriage(Util.isNull(marriageType) ? "" : marriageType);
        }
        //政治面貌
        if (Util.isNotNull(excelUserInfo.getPolitical())) {
            String politicalType = getLabelCodes(politicalList, excelUserInfo.getPolitical());
            excelUserInfo.setPolitical(Util.isNull(politicalType) ? "" : politicalType);
        }

        //户籍所在地
        if (Util.isNotNull(excelUserInfo.getLocation())) {
            String locationType = getLabelCodes(locationList, excelUserInfo.getLocation());
            excelUserInfo.setLocation(Util.isNull(locationType) ? "" : locationType);
        }
        //社保类型
        if (Util.isNotNull(excelUserInfo.getSocialSecurityType())) {
            String socialSecurityType = getLabelCodes(socialSecurityList, excelUserInfo.getSocialSecurityType());
            excelUserInfo.setSocialSecurityType(Util.isNull(socialSecurityType) ? "" : socialSecurityType);
        }
        //文化程度
        if (Util.isNotNull(excelUserInfo.getDegreeOfEducation())) {
            String degreeOfEducationType = getLabelCodes(educationList, excelUserInfo.getDegreeOfEducation());
            excelUserInfo.setDegreeOfEducation(Util.isNull(degreeOfEducationType) ? "" : degreeOfEducationType);
        }
        //养老状况
        if (Util.isNotNull(excelUserInfo.getPensionStatus())) {
            String pensionStatusType = getLabelCodes(pensionStatusList, excelUserInfo.getPensionStatus());
            excelUserInfo.setPensionStatus(Util.isNull(pensionStatusType) ? "" : pensionStatusType);
        }
        //养老机构
        if (Util.isNotNull(excelUserInfo.getPensionInstitutions())) {
            excelUserInfo.setPensionInstitutions(getOrgIdByMatchingOrgName(allPensionList, excelUserInfo.getPensionInstitutions()));
        }
        //居家状况
        if (Util.isNotNull(excelUserInfo.getLiveHomeStatus())) {
            String liveHomeStatusType = getLabelCodes(liveHomeStatusList, excelUserInfo.getLiveHomeStatus());
            excelUserInfo.setLiveHomeStatus(Util.isNull(liveHomeStatusType) ? "" : liveHomeStatusType);
        }
        //照顾人群
        if (Util.isNotNull(excelUserInfo.getCareCrowd())) {
            String careCrowdType = getLabelCodes(careCrowdList, excelUserInfo.getCareCrowd());
            excelUserInfo.setLiveHomeStatus(Util.isNull(careCrowdType) ? "" : careCrowdType);
        }
        //性别 1-男 2女
        if (Util.isNotNull(excelUserInfo.getUserSex())) {
            String userSex = SexTypeEnum.getEnumKey(excelUserInfo.getUserSex());
            excelUserInfo.setUserSex(Util.isNull(userSex) ? "" : userSex);
        }
        //常住人口(根据下拉框选择)  1-是 2-否
        if (Util.isNotNull(excelUserInfo.getIsLongStay())) {
            String isTrue = "是";
            String isFalse = "否";
            if (isTrue.equals(excelUserInfo.getIsLongStay())) {
                excelUserInfo.setIsLongStay("1");
            } else if (isFalse.equals(excelUserInfo.getIsLongStay())) {
                excelUserInfo.setIsLongStay("2");
            } else {
                excelUserInfo.setIsLongStay("2");
            }
        }
        //管辖行政区域
        if (Util.isNotNull(excelUserInfo.getBelongOrganization())) {
            excelUserInfo.setBelongOrganization(getOrgIdByMatchingOrgName(allSysOrganization, excelUserInfo.getBelongOrganization()));
        }
        //退休时间
        if (Util.isNotNull(excelUserInfo.getRetireTime())) {
            excelUserInfo.setRetireTime(excelUserInfo.getRetireTime().replace("-", ""));
        }
        //入驻时间
        if (Util.isNotNull(excelUserInfo.getCheckInTime())) {
            excelUserInfo.setCheckInTime(excelUserInfo.getCheckInTime().replace("-", ""));
        }

    }


    /**
     * @param excelUserInfo excelUserInfo
     * @param error         error
     * @param state         state
     * @return MsReportRecordLog
     */
    private ReportRecordLog getReportRecordLog(UserInfoExcel excelUserInfo, String error, int state) {
        ReportRecordLog recordLog = new ReportRecordLog();
        recordLog.setState(state);
        recordLog.setErrorMessage(error);
        recordLog.setCreateTime(new Date());
        BeanUtils.copyProperties(excelUserInfo, recordLog);
        return recordLog;
    }

    /**
     * 报表数据 转成 userInfo 对象
     *
     * @param excelUserInfo excelUserInfo
     * @return UserInfo
     */
    private UserInfo getUserInfo(UserInfoExcel excelUserInfo) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserNo(Constance.getStringRandom(18));
        userInfo.setCreateTime(new Date());
        userInfo.setStatus("1");
        BeanUtils.copyProperties(excelUserInfo, userInfo);

        //设置居住状况和管辖机构
        setLiveConditionAndBelongOrganization(userInfo);
        return userInfo;
    }


    /**
     * 获取所有组织架构
     */
    private List<SysOrganization> getAllSysOrganization() {
        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", "1");
        return sysOrganizationMapper.selectList(queryWrapper);

    }


    /**
     * 获取居民身份证信息
     *
     * @return List
     */
    private List<String> getUserPidList() {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        List<UserInfo> userInfos = userInfoMapper.selectList(userInfoQueryWrapper);
        List<String> userPidList = new ArrayList<>();
        userInfos.forEach(userInfo -> {
            try {
                userPidList.add(AesMyUtil.Decrypt(userInfo.getUserPid()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return userPidList;
    }

    /**
     * @param parentCode parentCode
     * @return YsLabelList
     */
    private List<YsLabel> getMsLabelList(String parentCode) {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARENT_CODE", parentCode);
        queryWrapper.eq("STATUS", "1");
        return ysLabelMapper.selectList(queryWrapper);
    }

    /**
     * 判断表头是否正确
     *
     * @param jsonObject 获取的表头
     */
    private Boolean isExcelHead(JSONObject jsonObject) {
        //表头 -为了验证表头是否一致
        String[] excelUserHead = new String[]{"*姓名", "*证件类型(根据下拉框选择)", "*证件号", "出生日期(例:1988-08-22)", "性别(根据下拉框选择)"
                , "民族(根据下拉框选择)", "*户籍地址", "*居住地址", "婚姻状况(根据下拉框选择)"
                , "政治面貌(根据下拉框选择)", "*户籍所在地区(根据下拉框选择)", "*常住人口(根据下拉框选择)"
                , "手机号码", "固定电话", "社保类型(根据下拉框选择)", "退休工资(单位: 元/月)", "退休单位", "退休时间(例:1985-05-01)"
                , "职业", "文化程度(根据下拉框选择)", "社保卡号", "*养老状况(根据下拉框选择)", "居家情况(根据下拉框选择)"
                , "照顾人群(根据下拉框选择)", "养老机构(根据下拉框选择)", "入驻时间(例:1985-05-01)", "健康描述(不超过300字)"
                , "长护险等级", "长护险有效期(例:1985-05-01)", "*管辖行政区域"
                , "第一联系人姓名", "第一联系人与老人关系(根据下拉框选择)", "第一联系人固定电话", "第一联系人详细地址", "第一联系人手机电话"
                , "第二联系人姓名", "第二联系人与老人关系(根据下拉框选择)", "第二联系人固定电话", "第二联系人详细地址", "第二联系人手机电话"
        };

        for (int i = 0; i < excelUserHead.length; i++) {
            if (!excelUserHead[i].equals(jsonObject.get(i + ""))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 排序
     */
    private void setSort(List<UserInfoExcel> excelUserInfoList) {
        int sort = 1;
        for (UserInfoExcel excelUserInfo : excelUserInfoList) {
            excelUserInfo.setSort(sort);
            sort++;
        }
    }

    /**
     * 标签类型 name 转成code
     *
     * @param labelList  labelList
     * @param labelNames labelNames
     * @return String
     */
    private String getLabelCodes(List<YsLabel> labelList, String labelNames) {
        String[] arr = labelNames.split(",");
        String labelCodes = "";
        for (String s : arr) {
            if (Util.isNotNull(s)) {
                for (YsLabel label : labelList) {
                    if (label.getLabelName().equals(s)) {
                        if (Util.isNotNull(labelCodes)) {
                            labelCodes += "," + label.getLabelCode();
                        } else {
                            labelCodes += label.getLabelCode();
                        }
                    }
                }
            }
        }
        return labelCodes;
    }


    /**
     * 获取 导出报表需要的数据
     *
     * @param reportId 报表 id
     * @return Map
     */
    public Map<String, Object> getErrorLogInfo(Integer reportId) {
        Map<String, Object> result = new HashMap<>(5);
        ReportRecord msReportRecord = reportRecordMapper.selectById(reportId);
        //导入类型 1-老人档案报表
        result.put("type", msReportRecord.getReportType());
        result.put("excelName", msReportRecord.getReportName());
        return result;
    }


    /**
     * 获取原始报表数据  居民信息
     *
     * @param reportId reportId 报表 id
     * @return List
     */
    public List<UserInfoExcel> getOriginalExcelUserInfo(Integer reportId) {
        List<UserInfoExcel> excelUserInfos = new ArrayList<>();
        List<ReportRecordLog> logList = getReportRecordLogList(reportId, null);
        logList.forEach(log -> {
            UserInfoExcel excelUserInfo = new UserInfoExcel();
            //解密手机号 和证件号
            aesMyUtilDecrypt(log);
            BeanUtils.copyProperties(log, excelUserInfo);
            excelUserInfos.add(excelUserInfo);
        });
        return excelUserInfos;
    }

    /**
     * 获取 居民 报表错误日志
     *
     * @param reportId 报表 id
     * @return List
     */
    public List<UserInfoExcelError> getExcelUserInfoError(Integer reportId) {
        List<UserInfoExcelError> excelUserInfoErrorList = new ArrayList<>();
        List<ReportRecordLog> logList = getReportRecordLogList(reportId, 9);
        logList.forEach(errorLog -> {
            UserInfoExcelError excelUserInfoError = new UserInfoExcelError();
            //解密手机号 和证件号
            aesMyUtilDecrypt(errorLog);
            BeanUtils.copyProperties(errorLog, excelUserInfoError);
            excelUserInfoErrorList.add(excelUserInfoError);
        });
        return excelUserInfoErrorList;
    }

    /**
     * 解密手机号 和证件号
     *
     * @param log ReportRecordLog
     */
    private void aesMyUtilDecrypt(ReportRecordLog log) {
        try {
            if (Util.isNotNull(log.getMobile())) {
                log.setMobile(AesMyUtil.Decrypt(log.getMobile()));
            }
            if (Util.isNotNull(log.getUserPid())) {
                log.setUserPid(AesMyUtil.Decrypt(log.getUserPid()));
            }
            if (Util.isNotNull(log.getBirthDate())) {
                if (log.getBirthDate().length() == 8) {
                    log.setBirthDate(transformDateForElderly(log.getBirthDate()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 获取日志集合
     *
     * @param reportId 报表 id
     * @return List
     */
    private List<ReportRecordLog> getReportRecordLogList(Integer reportId, Integer state) {
        QueryWrapper<ReportRecordLog> reportRecordLogQueryWrapper = new QueryWrapper<>();
        reportRecordLogQueryWrapper.eq("report_record_id", reportId);
        if (Util.isNotNull(state)) {
            reportRecordLogQueryWrapper.eq("state", state);
        }
        reportRecordLogQueryWrapper.orderByAsc("sort");
        return reportRecordLogMapper.selectList(reportRecordLogQueryWrapper);
    }


    private String getLabelName(String labelCode) {
        String labelName = "";
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.in("label_code", Arrays.asList(labelCode.split(",")));
        List<YsLabel> ysLabels = ysLabelMapper.selectList(queryWrapper);
        for (YsLabel ysLabel : ysLabels) {
            if (Util.isNotNull(labelName)) {
                labelName += "，" + ysLabel.getLabelName();
            } else {
                labelName = ysLabel.getLabelName();
            }
        }
        return labelName;
    }


    /**
     * 获取老人档案分页 便民服务
     *
     * @param status 状态 1-正常 8-去世 9-删除
     * @return Result
     */
    public Result<Object> getBmUserInfoPageList(BmUserinfoVo vo, String status, SysUser user) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //状态 1-正常 8-去世 9-删除
        queryWrapper.eq("status", status);
        //管辖行政区
        if (Util.isNotNull(vo.getBelongOrganization())) {
            queryWrapper.eq("belong_organization", vo.getBelongOrganization());
        }
        //性别
        if (Util.isNotNull(vo.getUserSex())) {
            queryWrapper.eq("user_sex", vo.getUserSex());
        }
        //姓名
        if (Util.isNotNull(vo.getUserName())) {
            queryWrapper.like("user_name", vo.getUserName());
        }
        //年龄
        if (Util.isNotNull(vo.getAge())) {
            if (vo.getAge() == 1) {
                queryWrapper.lt("age", 65);
            } else if (vo.getAge() == 2) {
                queryWrapper.between("age", 65, 69);
            } else if (vo.getAge() == 3) {
                queryWrapper.between("age", 70, 79);
            } else if (vo.getAge() == 4) {
                queryWrapper.between("age", 80, 89);
            } else if (vo.getAge() == 5) {
                queryWrapper.between("age", 90, 99);
            } else if (vo.getAge() == 6) {
                queryWrapper.gt("age", 100);
            }
        }
        //组织
        if (Util.isNotNull(vo.getOrgId())) {
            //获取节点子节点
            List<Long> allOrgIds = getAllOrgIds(vo.getOrgId());
            queryWrapper.in("belong_organization", allOrgIds);
        }
        //获取当前管理员组织节点
        HashSet<Long> sysUserOrgId = getSysUserOrgId(user);
        if (sysUserOrgId.size() > 0) {
            queryWrapper.in("belong_organization", sysUserOrgId);
        }

        //获取优惠表中所有老人
        Map<String, Object> params = new HashMap<>();
        params.put("type", vo.getType());
        params.put("orgIds", sysUserOrgId);
        List<String> userNoList = bmUserinfoMapper.getUserNoList(params);
        if (Util.isNotNull(userNoList) && userNoList.size() > 0) {
            //HashSet set = new HashSet<>(userNoList);
            queryWrapper.notIn("user_no", userNoList);
        }
        queryWrapper.eq("location", 1901);
        queryWrapper.orderByDesc("create_time");
        IPage<UserInfo> userInfoPage = userInfoMapper.selectPage(new Page<>(Long.parseLong(vo.getCurrentPage()), Long.parseLong(vo.getPageSize())), queryWrapper);
        //数据转化 页面展示
        userInfoPage.getRecords().forEach(this::transformBmUserInfoForPageList);

        List<UserInfo> userInfoList = userInfoPage.getRecords();
        return ResultUtil.getPageDataSuccess(new PageDo<>(Long.parseLong(vo.getCurrentPage()), Long.parseLong(vo.getPageSize()), Integer.parseInt(userInfoPage.getTotal() + ""), userInfoList));
    }

    /**
     * 通过身份证号 获取老人档案 身份信息
     *
     * @param userPid userPid
     * @return Result
     * @throws Exception Exception
     */
    public Result<Object> getUserInfoByUserPid(String userPid) throws Exception {

        UserInfo userInfo = getUserInfoWithUserPid(userPid);

        //长护险等级 和 有效时间
        if (Util.isNotNull(userInfo.getAssessmentLevel()) && Util.isNotNull(userInfo.getAssessmentValidDate())) {
            userInfo.setAssessmentValidDate(transformDateForElderly(userInfo.getAssessmentValidDate()));
            //跟老人院的 护理等级做匹配(name匹配 查到 显示 没查到 不显示)
            YsLabel ysLabel = ysLabelMapper.selectById(userInfo.getAssessmentLevel());
            List<YlCost> ylCosts = getYlCostByName(ysLabel.getLabelName());
            if (Util.isNotNull(ylCosts) && ylCosts.size() > 0) {
                userInfo.setAssessmentLevel(ylCosts.get(0).getCostNo() + "");
            } else {
                userInfo.setAssessmentLevel("");
                userInfo.setAssessmentValidDate("");
            }
        }
        if (Util.isNotNull(userInfo)) {
            userInfo.setUserInfoContactList(getUserInfoContactByUserNo(userInfo.getUserNo()));
        }
        return ResultUtil.getDataSuccess(userInfo);
    }


    /**
     * 老人档案  移档 操作
     *
     * @param userNo             userNo
     * @param belongOrganization belongOrganization
     * @return Result
     */
    public Result<Object> updateUserInfoBelongOrganization(String userNo, String belongOrganization) {

        if (Util.isNull(userNo) || Util.isNull(belongOrganization)) {
            return ResultUtil.errorMsg("未找到该老人或者选择的村居有误");
        }
        UserInfo userInfo = userInfoMapper.selectById(userNo);
        if (Util.isNull(userInfo)) {
            return ResultUtil.errorMsg("未找到该老人档案");
        }

        userInfo.setBelongOrganization(belongOrganization);
        userInfoMapper.updateById(userInfo);
        return ResultUtil.success();
    }


    private List<YlCost> getYlCostByName(String name) {
        if (Util.isNull(name)) {
            return null;
        }
        QueryWrapper<YlCost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("COST_NAME", name);
        queryWrapper.eq("STATUS", "1");
        return ylCostMapper.selectList(queryWrapper);

    }


    public UserInfo getUserInfoWithUserPid(String userPid) throws Exception {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_pid", AesMyUtil.Encrypt(userPid));
        queryWrapper.eq("status", "1");
        return userInfoMapper.selectOne(queryWrapper);
    }


    /**
     * 获取当前管理员组织架构 便民服务
     */
    private HashSet<Long> getSysUserOrgId(SysUser user) {
        //查询当前管理员类型为3得节点
        Map<String, Object> param = new HashMap<>(10);
        param.put("userNo", user.getUserNo());
        param.put("type", "3");
        List<Map<String, Object>> orgList = sysOrganizationMapper.selectOrgIdsByUserNoAndType(param);
        HashSet<Long> longs = new HashSet<>();
        for (Map<String, Object> map : orgList) {
            String[] codes = map.get("orgPathCode").toString().split(",");
            for (String code : codes) {
                longs.add(Long.parseLong(code));
            }
        }
        return longs;
    }

    /**
     * 获取当前节点所有子节点 便民服务
     */
    private List<Long> getAllOrgIds(String orgId) {
        ArrayList<Long> orgIds = new ArrayList<>(10);
        List<Map<String, Object>> list = sysOrganizationMapper.getAllOrganization(orgId);
        for (Map<String, Object> map : list) {
            orgIds.add(Long.parseLong(map.get("orgId").toString()));
        }
        return orgIds;
    }


    /**
     * 获取养老机构
     *
     * @return List
     */
    public List<SysOrganization> getPensionOrgList() {
        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        //组织类型 1-管理 2-服务中心 3-村/社区 4-养老机构
        queryWrapper.eq("type", "4");
        queryWrapper.eq("state", "1");
        return sysOrganizationMapper.selectList(queryWrapper);
    }


    //-----------------------------   以下为数据看板的统计数据        ---------------------------------------------------

    /**
     * 获取所有片区       片区 为 组织架构末节点的上一层
     *
     * @return List
     */
    private List<Map<String, Object>> getAllOrgOfArea() {
        //片区的level 片区 为 组织架构末节点的上一层
        Integer level = userInfoMapper.getAreaOrgLevel(getUser().getUserNo());
        if (level == 0 || Util.isNull(level)) {
            return null;
        }
        return userInfoMapper.getAllAreaOrg(level + "");
    }


    /**
     * 获取 统计数据
     * <p>
     * 片区 为 组织架构末节点的上一层  , 村级别为组织架构的末节点
     *
     * @return Result
     */
    public Result<Object> getStatisticsData() {
        Map<String, Object> resultMap = new HashMap<>();

        //--------------获取 userInfo 总数量 -------------------------
        Integer userInfoTotalCount = userInfoMapper.getUserInfoCount();

        //--------------获取 各个片区的总数量 -------------------------
        // 获取所有片区       片区 为 组织架构末节点的上一层
        List<Map<String, Object>> allOrgOfArea = getAllOrgOfArea();
        if (Util.isNull(allOrgOfArea)) {
            return ResultUtil.errorMsg("获取片区数据失败");
        }
        allOrgOfArea.forEach(map -> {
            String orgId = map.get("orgId").toString();
            SysOrganization organization = sysOrganizationMapper.selectById(orgId);
            //获取下面子节点
            getOrganizationByOrgId(organization);


            //--------------（社区人口分布）获取 各个片区  村的数量 -------------------------
            List<String> orgIds = new ArrayList<>();
            getOrgIds(orgIds, organization);
            List<Map<String, Object>> subList = userInfoMapper.getCountSubOrg(orgIds);
            if (subList.size() < 10) {
                int limit = 10;
                Map<String, Object> subParams = new HashMap<>();
                subParams.put("limitSize", limit - subList.size());
                List<String> notInOrgIds = new ArrayList<>();
                subParams.put("isSize", subList.size());
                if (subList.size() == 0) {
                    subParams.put("notInOrgIds", orgIds);
                } else {
                    subList.forEach(subMap -> notInOrgIds.add(subMap.get("orgId") + ""));
                    subParams.put("notInOrgIds", notInOrgIds);
                }
                subParams.put("parentOrgId", orgId);
                List<Map<String, Object>> subListOther = userInfoMapper.getCountSubOrgOther(subParams);
                subList.addAll(subListOther);
            }
            //排序
            subList.sort(Comparator.comparingInt((Map<String, Object> subMap) -> Integer.parseInt(Util.isNull(subMap.get("count")) ? "0" : subMap.get("count").toString())));

            if (subList.size() > 10) {
                subList = subList.subList(subList.size() - 10, subList.size());
            }
            //--------------（社区人口分布）获取 各个片区  村的数量 -------------------------

            map.put("subOrgList", subList);
            //放置Arr
            arrangementMap(subList, map);
            //获取每个片区的人数总量
            map.put("count", getUserInfoCount(orgIds));
        });


        //userInfo 总数量
        resultMap.put("userInfoTotalCount", userInfoTotalCount);
        //各个片区的userInfo 总数  和子结构的 数量
        resultMap.put("orgAreaOfCount", allOrgOfArea);
        //户籍分布列表
        // distributionSituation(resultMap);
        //年龄分布
        getAgeDistribution(resultMap);

        //照顾人群（特别关注）
        getCareCrowdStatistics(resultMap);
        //社保类型  统计
        getSocialSecurityTypeStatistics(resultMap);
        //居住状态 统计
        getLivingStatistics(allOrgOfArea, resultMap);
        //户籍人口数
        resultMap.put("locationCount", getLocationUserInfoCount());
        //常住人口数
        resultMap.put("isLongStayCount", getIsLongStayCount());

        return ResultUtil.getDataSuccess(resultMap);
    }

    private Integer getLocationUserInfoCount() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //1901-安亭镇
        queryWrapper.eq("location", "1901");
        queryWrapper.eq("status", "1");
        return userInfoMapper.selectCount(queryWrapper);
    }

    private Integer getIsLongStayCount() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_long_stay", "1");
        queryWrapper.eq("status", "1");
        return userInfoMapper.selectCount(queryWrapper);
    }


    /**
     * 户籍分布列表
     * 若有值，则必定是住在安亭镇内的某村的，若=NULL则代表不住在安亭
     * 常住在安亭镇的老人总数，指的是 居住所在组织ID<>null and status=健在
     * 本市户籍老人总数，指的是 居住所在组织ID<>null and status=健在 and 户籍类型=本市
     * 本市户籍，嘉定镇内老人总数，指的是 居住所在组织ID<>null and status=健在 and 户籍类型=本市 and 户籍所在地区=嘉定镇内
     * 本市户籍，嘉定镇外老人总数，指的是 居住所在组织ID<>null and status=健在 and 户籍类型=本市 and 户籍所在地区=嘉定镇外
     * 本市户籍，嘉定镇内老人总数(其他)，指的是 居住所在组织ID<>null and status=健在 and 户籍类型=本市 and 户籍所在地区=其他
     * 外地 老人总数，指的是 居住所在组织ID<>null and status=健在 and 户籍类型=外地
     * 海外 老人总数，指的是 居住所在组织ID<>null and status=健在 and 户籍类型=海外
     */
    private void distributionSituation(Map<String, Object> resultMap) {

        Integer residentPopulationCount = getDistributionSituationCount(null, null);
        Integer thisCityHouseholdRegisterCount = getDistributionSituationCount(HouseholdRegisterEnum.BD.getKey(), null);
        Integer inTownCount = getDistributionSituationCount(HouseholdRegisterEnum.BD.getKey(), LocationEnum.JDZN.getKey());
        //        Integer outTownCount = getDistributionSituationCount(HouseholdRegisterEnum.BD.getKey(), LocationEnum.JDZW.getKey());
        Integer townOtherCount = getDistributionSituationCount(HouseholdRegisterEnum.BD.getKey(), LocationEnum.QT.getKey());
        Integer fieldCount = getDistributionSituationCount(HouseholdRegisterEnum.WD.getKey(), null);
        Integer overseasCount = getDistributionSituationCount(HouseholdRegisterEnum.HW.getKey(), null);

        //常住在安亭镇的老人总数
        resultMap.put("residentPopulationCount", residentPopulationCount);
        //本市户籍老人总数
        resultMap.put("thisCityHouseholdRegisterCount", thisCityHouseholdRegisterCount);
        //本市户籍,嘉定镇内老人总数
        resultMap.put("inTownCount", inTownCount);
        //本市户籍,嘉定镇外老人总数
        resultMap.put("outTownCount", "0");
        //本市户籍,嘉定其他老人总数
        resultMap.put("townOtherCount", townOtherCount);
        //外地
        resultMap.put("fieldCount", fieldCount);
        //海外
        resultMap.put("overseasCount", overseasCount);

        //------------------户籍分布列表 大饼图 数据---------------------
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(getPieChartMap(LocationEnum.JDZN.getValue(), inTownCount));
        //        list.add(getPieChartMap(LocationEnum.JDZW.getValue(), outTownCount));
        list.add(getPieChartMap(LocationEnum.QT.getValue(), townOtherCount));
        list.add(getPieChartMap(HouseholdRegisterEnum.WD.getValue(), fieldCount));
        list.add(getPieChartMap(HouseholdRegisterEnum.HW.getValue(), overseasCount));
        resultMap.put("distributionSituationPieChart", list);

    }

    private Map<String, Object> getPieChartMap(String name, Object value) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("name", name);
        map.put("value", value);
        return map;
    }

    /**
     * 获取
     *
     * @param householdRegister 户籍
     * @param location          所在地区
     * @return Integer
     */
    private Integer getDistributionSituationCount(String householdRegister, String location) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        //居住所在行政区域
        queryWrapper.isNotNull("live_area_of_residence");

        //户籍类型
        if (Util.isNotNull(householdRegister)) {
            queryWrapper.eq("household_register", householdRegister);
        }
        //所在地区
        if (Util.isNotNull(location)) {
            queryWrapper.eq("location", location);
        }
        return userInfoMapper.selectCount(queryWrapper);
    }


    /**
     * 男女分布情况
     */
    private void getAgeDistribution(Map<String, Object> resultMap) {

        //-------------1.情况 不分男女-------------------
        //老人年龄分布
        Integer ageWithoutSexOne = getAgeOfSex(null, 1);
        Integer ageWithoutSexTwo = getAgeOfSex(null, 2);
        Integer ageWithoutSexThree = getAgeOfSex(null, 3);
        Integer ageWithoutSexFour = getAgeOfSex(null, 4);
        Integer ageWithoutSexFive = getAgeOfSex(null, 5);
        Integer ageWithoutSexSix = getAgeOfSex(null, 6);

        List<Map<String, Object>> ageDistributionList = new ArrayList<>();
        ageDistributionList.add(getPieChartMap("60岁以下", ageWithoutSexOne));
        ageDistributionList.add(getPieChartMap("60-69岁", ageWithoutSexTwo));
        ageDistributionList.add(getPieChartMap("70-79岁", ageWithoutSexThree));
        ageDistributionList.add(getPieChartMap("80-89岁", ageWithoutSexSix));
        ageDistributionList.add(getPieChartMap("90-99岁", ageWithoutSexFour));
        ageDistributionList.add(getPieChartMap("100岁及以上", ageWithoutSexFive));
        resultMap.put("ageDistribution", ageDistributionList);

        //-------------2.情况 分男女-------------------
        String[] ageWithoutSexNameArr = new String[]{"60岁以下", "60-69岁", "70-79岁", "80-89岁", "90-99岁", "100岁及以上"};
        resultMap.put("ageDistributionNameArr", ageWithoutSexNameArr);
        //男
        Integer ageManOne = getAgeOfSex(1, 1);
        Integer ageManTwo = getAgeOfSex(1, 2);
        Integer ageManThree = getAgeOfSex(1, 3);
        Integer ageManFour = getAgeOfSex(1, 4);
        Integer ageManFive = getAgeOfSex(1, 5);
        //80-89岁
        Integer ageManSix = getAgeOfSex(1, 6);
        Integer[] ageDistributionManCountArr = new Integer[]{ageManFive == 0 ? 0 : -ageManFive
                , ageManFour == 0 ? 0 : -ageManFour
                , ageManSix == 0 ? 0 : -ageManSix
                , ageManThree == 0 ? 0 : -ageManThree
                , ageManTwo == 0 ? 0 : -ageManTwo
                , ageManOne == 0 ? 0 : -ageManOne};
        resultMap.put("ageDistributionManCountArr", ageDistributionManCountArr);

        //女
        Integer ageWomanOne = getAgeOfSex(2, 1);
        Integer ageWomanTwo = getAgeOfSex(2, 2);
        Integer ageWomanThree = getAgeOfSex(2, 3);
        Integer ageWomanFour = getAgeOfSex(2, 4);
        Integer ageWomanFive = getAgeOfSex(2, 5);
        //80-89岁
        Integer ageWomanSix = getAgeOfSex(2, 6);
        Integer[] ageDistributionWoManCountArr = new Integer[]{ageWomanFive, ageWomanFour, ageWomanSix, ageWomanThree, ageWomanTwo, ageWomanOne};
        resultMap.put("ageDistributionWoManCountArr", ageDistributionWoManCountArr);
    }


    /**
     * social_security_type 社保类型  统计
     */
    private void getSocialSecurityTypeStatistics(Map<String, Object> resultMap) {

        List<Map<String, Object>> socialSecurityTypeList = new ArrayList<>();
        socialSecurityTypeList.add(getPieChartMap(SocialSecurityTypeEnum.CB.getValue(), getSocialSecurityTypeUserInfoCount(SocialSecurityTypeEnum.CB.getKey())));
        socialSecurityTypeList.add(getPieChartMap(SocialSecurityTypeEnum.ZB.getValue(), getSocialSecurityTypeUserInfoCount(SocialSecurityTypeEnum.ZB.getKey())));
        socialSecurityTypeList.add(getPieChartMap(SocialSecurityTypeEnum.JB.getValue(), getSocialSecurityTypeUserInfoCount(SocialSecurityTypeEnum.JB.getKey())));
        socialSecurityTypeList.add(getPieChartMap(SocialSecurityTypeEnum.NB.getValue(), getSocialSecurityTypeUserInfoCount(SocialSecurityTypeEnum.NB.getKey())));
        socialSecurityTypeList.add(getPieChartMap(SocialSecurityTypeEnum.ZDYL.getValue(), getSocialSecurityTypeUserInfoCount(SocialSecurityTypeEnum.ZDYL.getKey())));
        resultMap.put("socialSecurityTypeList", socialSecurityTypeList);
    }


    /**
     * 社保类型 数量
     *
     * @param socialSecurityType 社保类型
     */
    private Integer getSocialSecurityTypeUserInfoCount(String socialSecurityType) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.eq("social_security_type", socialSecurityType);
        return userInfoMapper.selectCount(queryWrapper);
    }

    /**
     * CareCrowdEnum  照顾人群
     */
    private void getCareCrowdStatistics(Map<String, Object> resultMap) {
        List<Map<String, Object>> careCrowdList = new ArrayList<>();
        careCrowdList.add(getPieChartMap(CareCrowdEnum.CJR.getValue(), getCareCrowdUserInfoCount(CareCrowdEnum.CJR.getKey())));
        careCrowdList.add(getPieChartMap(CareCrowdEnum.DB.getValue(), getCareCrowdUserInfoCount(CareCrowdEnum.DB.getKey())));
        careCrowdList.add(getPieChartMap(CareCrowdEnum.DSR.getValue(), getCareCrowdUserInfoCount(CareCrowdEnum.DSR.getKey())));
        careCrowdList.add(getPieChartMap(CareCrowdEnum.SD.getValue(), getCareCrowdUserInfoCount(CareCrowdEnum.SD.getKey())));
        careCrowdList.add(getPieChartMap(CareCrowdEnum.TWJR.getValue(), getCareCrowdUserInfoCount(CareCrowdEnum.TWJR.getKey())));
        resultMap.put("careCrowdList", careCrowdList);
    }

    /**
     * 照顾人群 数量
     *
     * @param careCrowdType 社保类型
     */
    private Integer getCareCrowdUserInfoCount(String careCrowdType) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.like("care_crowd", careCrowdType);
        return userInfoMapper.selectCount(queryWrapper);
    }


    /**
     * 居家状况
     */
    private void getLivingStatistics(List<Map<String, Object>> allOrgOfArea, Map<String, Object> resultMap) {

        List<Object> livingHomeData = new ArrayList<>();
        List<Integer> forMaxNumList = new ArrayList<>();
        allOrgOfArea.forEach(map -> {
            String orgId = map.get("orgId").toString();
            SysOrganization organization = sysOrganizationMapper.selectById(orgId);
            getOrganizationByOrgId(organization);
            List<String> orgIds = new ArrayList<>();
            getOrgIds(orgIds, organization);
            List<Integer> numList = new ArrayList<>();
            numList.add(getLivingStatusCount(orgIds, LiveHomeStatusEnum.DJ.getKey()));
            numList.add(getLivingStatusCount(orgIds, LiveHomeStatusEnum.CL.getKey()));
            numList.add(getLivingStatusCount(orgIds, LiveHomeStatusEnum.YFMTZ.getKey()));
            numList.add(getLivingStatusCount(orgIds, LiveHomeStatusEnum.YZNTZQT.getKey()));
            forMaxNumList.addAll(numList);
            livingHomeData.add(numList.toArray());
        });

        //居家状况 数据
        resultMap.put("livingHomeData", livingHomeData);
        //居家状况 nameArr
        resultMap.put("livingHomeNameArr", LiveHomeStatusEnum.getNameArr());

        //获取最大值和间隔值
        Map<String, Object> maxAndIntervalMap = getMaxAndInterval(forMaxNumList);
        resultMap.put("livingHomeMax", maxAndIntervalMap.get("max"));
        resultMap.put("livingHomeInterval", maxAndIntervalMap.get("interval"));

    }


    /**
     * 获取最大值和间隔值
     */
    private Map<String, Object> getMaxAndInterval(List<Integer> numArr) {
        Map<String, Object> result = new HashMap<>(5);
        Integer max = 0;
        if (numArr.size() > 0) {
            max = Collections.max(numArr);
        }
        max = ((max / 100) + 1) * 100;
        //间隔值
        Integer interval = max / 5;
        result.put("max", max);
        result.put("interval", interval);
        return result;
    }


    private Integer getLivingStatusCount(List<String> orgIds, String livingHomeStatus) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.like("live_home_status", livingHomeStatus);
        queryWrapper.in("belong_organization", orgIds);
        return userInfoMapper.selectCount(queryWrapper);
    }


    /**
     * 获取 年龄的数量
     *
     * @param isSex  1-男 2-女
     * @param sexNum 1-60岁以下  2- 60-69岁 3 - 70-79岁 4-90-99岁 5-100岁及以上
     * @return Integer
     */
    private Integer getAgeOfSex(Integer isSex, Integer sexNum) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        //年龄段
        int one = 1;
        int two = 2;
        int three = 3;
        int four = 4;
        int five = 5;
        int six = 6;
        if (Util.isNotNull(sexNum)) {
            if (one == sexNum) {
                queryWrapper.lt("age", 60);
            } else if (two == sexNum) {
                queryWrapper.between("age", 60, 69);
            } else if (three == sexNum) {
                queryWrapper.between("age", 70, 79);
            } else if (four == sexNum) {
                queryWrapper.between("age", 90, 99);
            } else if (five == sexNum) {
                queryWrapper.ge("age", 100);
            } else if (six == sexNum) {
                queryWrapper.between("age", 80, 89);
            }
        }
        if (Util.isNotNull(isSex)) {
            queryWrapper.eq("user_sex", isSex);
        }

        return userInfoMapper.selectCount(queryWrapper);
    }


    /**
     * 转化成数组
     *
     * @param list    list
     * @param mainMap mainMap
     */
    public void arrangementMap(List<Map<String, Object>> list, Map<String, Object> mainMap) {
        List<String> nameList = new ArrayList<>();
        List<String> numStr = new ArrayList<>();
        list.forEach(map -> {
            nameList.add(map.get("orgName").toString());
            numStr.add(map.get("count").toString());
        });
        mainMap.put("orgNameArr", nameList.toArray());
        mainMap.put("countArr", numStr.toArray());
    }

    /**
     * 获取 各个片区下面 各组织的 人口数量
     *
     * @param subList      subList
     * @param organization organization
     */
    public void getSubOrgNameAndCountList(List<Map<String, Object>> subList, SysOrganization organization) {
        if (Util.isNotNull(organization.getChildren()) && organization.getChildren().size() > 0) {
            return;
        }

        List<SysOrganization> subOrganizationList = getOrganizationByParentId(organization.getOrgId() + "");
        subOrganizationList.forEach(org -> {
            Map<String, Object> map = new HashMap<>();
            map.put("orgName", org.getOrgName());
            map.put("count", getUserInfoCountSingle(org));
            subList.add(map);
            if (Util.isNotNull(org.getChildren()) && org.getChildren().size() > 0) {
                org.getChildren().forEach(orgChild -> getSubOrgNameAndCountList(subList, orgChild));
            }
        });
    }


    /**
     * 获取 单个 的组织下的userInfo的数量
     *
     * @param organization organization
     * @return Integer
     */
    public Integer getUserInfoCountSingle(SysOrganization organization) {
        //        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //        queryWrapper.eq("status", "1");
        //        queryWrapper.eq("belong_organization", organization.getOrgId());
        return userInfoMapper.getCountOrg(organization.getOrgId() + "");
    }


    /**
     * 获取组织下 全部 的userInfo的数量
     *
     * @param orgIds orgIds
     * @return Integer
     */
    public Integer getUserInfoCount(List<String> orgIds) {
        //获取数量
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.in("belong_organization", orgIds);
        return userInfoMapper.selectCount(queryWrapper);
    }

    public void getOrgIds(List<String> orgIds, SysOrganization organization) {
        if (Util.isNull(organization)) {
            return;
        }
        orgIds.add(organization.getOrgId() + "");
        //getOrganizationByOrgId(organization);
        List<SysOrganization> subOrganizationList = organization.getChildren();
        if (Util.isNotNull(subOrganizationList) && subOrganizationList.size() > 0) {
            subOrganizationList.forEach(model -> getOrgIds(orgIds, model));
        }
    }


    public void getOrganizationByOrgId(SysOrganization organization) {
        //子节点 查询
        List<SysOrganization> subOrganizationList = getOrganizationByParentId(organization.getOrgId() + "");
        if (Util.isNotNull(subOrganizationList) && subOrganizationList.size() > 0) {
            organization.setChildren(subOrganizationList);
            subOrganizationList.forEach(this::getOrganizationByOrgId);
        }
    }


    private List<SysOrganization> getOrganizationByParentId(String parentOrgId) {
        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", "1");
        queryWrapper.eq("parent_org_id", parentOrgId);
        return sysOrganizationMapper.selectList(queryWrapper);
    }


    /**
     * 照顾人群数据
     */
    public Result<Object> getCareCrowdDataChart(String careCrowLabelCode) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Integer> getMaxAndIntervalTotal = new ArrayList<>();

        // 获取所有片区       片区 为 组织架构末节点的上一层
        List<Map<String, Object>> orgOfArea = getAllOrgOfArea();
        if (Util.isNull(orgOfArea)) {
            return ResultUtil.errorMsg("获取片区数据失败");
        }

        orgOfArea.forEach(map -> {
            Map<String, Object> dataMap = new HashMap<>(10);
            SysOrganization organization = sysOrganizationMapper.selectById(map.get("orgId").toString());
            //获取下面子节点
            getOrganizationByOrgId(organization);
            List<String> nameList = new ArrayList<>();
            List<Integer> countList = new ArrayList<>();
            if (Util.isNotNull(organization.getChildren()) && organization.getChildren().size() > 0) {
                organization.getChildren().forEach(childOrg -> getCareCrowOrgNameArr(careCrowLabelCode, nameList, countList, childOrg));
            }
            getMaxAndIntervalTotal.addAll(countList);
            dataMap.put("orgName", organization.getOrgName());
            dataMap.put("careCrowdOrgNameArr", nameList.toArray());
            dataMap.put("careCrowdCountArr", countList.toArray());
            resultList.add(dataMap);
        });


        Map<String, Object> maxAndIntervalMap = getMaxAndInterval(getMaxAndIntervalTotal);
        Map<String, Object> result = new HashMap<>(10);
        result.put("list", resultList);
        result.put("max", maxAndIntervalMap.get("max"));
        result.put("interval", maxAndIntervalMap.get("interval"));

        return ResultUtil.getDataSuccess(result);
    }


    /**
     * 照顾人群数据 的名称 集合
     */
    private void getCareCrowOrgNameArr(String careCrowLabelCode, List<String> nameList, List<Integer> countList, SysOrganization organization) {
        if (Util.isNotNull(organization)) {
            nameList.add(organization.getOrgName());
            countList.add(getCareCrowUserInfoCount(String.valueOf(organization.getOrgId()), careCrowLabelCode));
        }
        if (Util.isNotNull(organization.getChildren()) && organization.getChildren().size() > 0) {
            organization.getChildren().forEach(childOrg -> getCareCrowOrgNameArr(careCrowLabelCode, nameList, countList, childOrg));
        }
    }

    private Integer getCareCrowUserInfoCount(String orgId, String careCrowLabelCode) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.eq("belong_organization", orgId);
        queryWrapper.like("care_crowd", careCrowLabelCode);
        return userInfoMapper.selectCount(queryWrapper);
    }

    /**
     * 是否是末节点组织架构
     */
    public Boolean isTerminalNodeOrg(String orgId) {
        Integer level = userInfoMapper.getAreaOrgLevel(getUser().getUserNo()) + 1;
        SysOrganization sysOrganization = sysOrganizationMapper.selectById(orgId);
        if (Util.isNull(level) || Util.isNull(sysOrganization)) {
            return false;
        }
        return level.toString().equals(sysOrganization.getOrgLevel());
    }


    public Result<Object> getOrganizationOfMultiple() {
        Integer level = userInfoMapper.getAreaOrgLevel(getUser().getUserNo());

        QueryWrapper<SysOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "1");
        queryWrapper.eq("state", "1");
        queryWrapper.eq("org_level", level);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("children", sysOrganizationMapper.selectList(queryWrapper));
        return ResultUtil.getDataSuccess(resultMap);
    }


    public List<DownUserInfoExcel> getDownUserInfoExcelReportData(UserInfoVO vo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //状态 1-正常 8-去世 9-删除
        queryWrapper.eq("status", "1");
        //列表页 查询条件给queryWrapper 赋值
        setQueryWrapperForQueryUserInfo(queryWrapper, vo);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        List<DownUserInfoExcel> downUserInfoExcels = new ArrayList<>();

        userInfoList.forEach(model -> {
            transformUserInfoForPageList(model);
            DownUserInfoExcel downUserInfoExcel = new DownUserInfoExcel();
            BeanUtils.copyProperties(model, downUserInfoExcel);
            downUserInfoExcels.add(downUserInfoExcel);
        });
        return downUserInfoExcels;
    }


    /**
     * 获取老人历史记录
     */
    public Result<Object> getUserInfoHistoryPageList(UserInfoVO userInfoVO) {

        QueryWrapper<UserInfoHistory> queryWrapper = new QueryWrapper<>();
        if (Util.isNotNull(userInfoVO.getSearchContent())) {
            queryWrapper.eq("user_name", userInfoVO.getSearchContent());
        }
        if (Util.isNotNull(userInfoVO.getOrgId())) {
            queryWrapper.eq("old_belong_organization", userInfoVO.getOrgId());
        }
        queryWrapper.orderByDesc("create_time");

        IPage<UserInfoHistory> infoHistoryIPage = userInfoHistoryMapper.selectPage(new Page<>(userInfoVO.getCurrentPage(), userInfoVO.getPageSize()), queryWrapper);
        List<UserInfoHistory> userInfoHistoryList = infoHistoryIPage.getRecords();

        userInfoHistoryList.forEach(model -> {
            model.setNewBelongOrganizationName(sysOrganizationMapper.selectById(model.getNewBelongOrganization()).getOrgName());
            model.setOldBelongOrganizationName(sysOrganizationMapper.selectById(model.getOldBelongOrganization()).getOrgName());
        });

        return ResultUtil.getPageDataSuccess(new PageDo<>(userInfoVO.getCurrentPage(), userInfoVO.getPageSize(), Integer.parseInt(infoHistoryIPage.getTotal() + ""), userInfoHistoryList));
    }


}
